Mar*_*rke 17 .net c# reflection
我希望能够从.NET中的堆栈帧获取所有参数值.有点像在Visual Studio调试器中看到调用堆栈中的值的方式.我的方法集中在使用StackFrame类,然后反映在ParameterInfo数组上.我在反射和属性方面取得了成功,但事实证明这有点棘手.
有没有办法实现这一目标?
到目前为止,代码如下所示:
class Program
{
static void Main(string[] args)
{
A a = new A();
a.Go(1);
}
}
public class A
{
internal void Go(int x)
{
B b = new B();
b.Go(4);
}
}
public class B
{
internal void Go(int y)
{
Console.WriteLine(GetStackTrace());
}
public static string GetStackTrace()
{
StringBuilder sb = new StringBuilder();
StackTrace st = new StackTrace(true);
StackFrame[] frames = st.GetFrames();
foreach (StackFrame frame in frames)
{
MethodBase method = frame.GetMethod();
sb.AppendFormat("{0} - {1}",method.DeclaringType, method.Name);
ParameterInfo[] paramaters = method.GetParameters();
foreach (ParameterInfo paramater in paramaters)
{
sb.AppendFormat("{0}: {1}", paramater.Name, paramater.ToString());
}
sb.AppendLine();
}
return sb.ToString();
}
}
Run Code Online (Sandbox Code Playgroud)
SfApp.B - GetStackTrace
SfApp.B - Go
y: Int32 y
SfApp.A - Go
x: Int32 x
SfApp.Program - Main
args: System.String[] args
Run Code Online (Sandbox Code Playgroud)
SfApp.B - GetStackTrace
SfApp.B - Go
y: 4
SfApp.A - Go
x: 1
SfApp.Program - Main
Run Code Online (Sandbox Code Playgroud)
仅仅为了一些上下文,我的计划是在我抛出自己的异常时尝试使用它.我会更详细地看看你的建议,看看我是否能看到它合适.
似乎不可能那样做.它仅提供有关方法及其参数的元信息.不是callstack时的实际值.
有人建议从ContextBoundObject派生您的类,并使用IMessageSink通知所有方法调用和参数值.这通常用于.NET Remoting.
另一个建议可能是编写调试器.这就是IDE获取其信息的方式.Microsoft有Mdbg,您可以从中获取源代码.或者写一个CLR分析器.
归档时间: |
|
查看次数: |
7538 次 |
最近记录: |