How to get a dump of all local variables?

后端 未结 3 629
旧巷少年郎
旧巷少年郎 2020-12-08 15:34

How can I get a dump of all local & session variables when an exception occurs? I was thinking of writing some sort of reflection based function that would interrogate t

3条回答
  •  不知归路
    2020-12-08 16:09

    I'm not sure if this is what you're looking for. But if you're in a catch-block you can get all fields and properties of this class in the following way:

    try
    {
        double d = 1 / 0;
    }
    catch (Exception ex)
    {
        var trace = new System.Diagnostics.StackTrace();
        var frame = trace.GetFrame(1);
        var methodName = frame.GetMethod().Name;
        var properties = this.GetType().GetProperties();
        var fields = this.GetType().GetFields(); // public fields
        // for example:
        foreach (var prop in properties)
        {
            var value = prop.GetValue(this, null);
        }
        foreach (var field in fields)
        {
            var value = field.GetValue(this);
        }
        foreach (string key in Session) 
        {
            var value = Session[key];
        }
    }
    

    I've showed how to get the method name where the exception occured only for the sake of completeness.

    • Type.GetProperties Method
    • Type.GetFields Method
    • PropertyInfo.GetValue Method
    • FieldInfo.GetValue Method
    • StackTrace Class

    With BindingFlags you can specify constraints, for example that you only want properties of this class and not from inherited:

    Using GetProperties() with BindingFlags.DeclaredOnly in .NET Reflection

    Of course the above should give you only a starting-point how to do it manually and you should encapsulate all into classes. I've never used it myself so it's untested.

提交回复
热议问题