Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
144 views
in Technique[技术] by (71.8m points)

c# - How to get a dump of all local variables?

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 the calling function & create a dump of variables & values.

Is there an existing library that I can use?

UPDATE

After speaking to a colleague, I was pointed to AOP or Aspect Oriented Programming. Here is what I understand ... Using AOP, one would simple decorate the methods & classes with certain attributes. AOP framework then injects code in or around these classes & methods. There are two separate kinds of framework, one that injects code & then compiles the assembly & the second simply uses reflection & traps the call which you have decorated and wraps whatever code around the method at runtime.

I hope all that makes sense. I will be doing more research on this & post my approach.

Thanks guys ...

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...