如何获取所有局部变量的转储? [英] 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?
更新
在与同事交谈之后,我被指向AOP或面向方面的编程。这是我的理解...使用AOP,一个简单的装饰方法&具有某些属性的类。 AOP框架然后在这些类中或周围注入代码方法。有两种不同的框架,一种是注入代码和然后编译程序集第二个只是使用反射&捕获您在运行时对方法进行了修改的任何代码。
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.
谢谢你们...
推荐答案
不知道这是你要找的东西。但是如果你是一个catch块,你可以通过以下方式获得该类的所有字段和属性:
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
使用 BindingFlags ,您可以指定约束,例如,您只希望此类的属性,而不是继承:
With BindingFlags you can specify constraints, for example that you only want properties of this class and not from inherited:
使用.NET中的BindingFlags.DeclaredOnly使用GetProperties()
当然,上面的内容只能给出一个起始点,如何手动执行,你应该将所有内容封装到类中。我从来没有使用过它,因此它是未经测试的。
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.
这篇关于如何获取所有局部变量的转储?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!