如何获取所有局部变量的转储? [英] 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-block 中,你可以通过以下方式获得这个类的所有字段和属性:
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.
使用 BindingFlags,您可以指定约束,例如你只想要这个类的属性而不是继承的:
With BindingFlags you can specify constraints, for example that you only want properties of this class and not from inherited:
在 .NET 反射中使用 GetProperties() 和 BindingFlags.DeclaredOnly
当然,上面应该只为您提供一个如何手动完成的起点,您应该将所有内容封装到类中.我自己从未使用过,因此未经测试.
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屋!