Capturing method state using Reflection

2020-02-10 08:10发布

Is there a way to use .NET reflection to capture the values of all parameters/local variables?

6条回答
smile是对你的礼貌
2楼-- · 2020-02-10 08:29

Reflection is not used to capture information from the stack. It reads the Assembly.

You might want to take a look at StackTrace

http://msdn.microsoft.com/en-us/library/system.diagnostics.stacktrace.aspx

Good article here:

http://www.codeproject.com/KB/trace/customtracelistener.aspx

查看更多
来,给爷笑一个
3楼-- · 2020-02-10 08:33

Reflection will tell you the type of parameters that a method has but it won't help discover their values during any particular invocation. Reflection doesn't tell you anything about local variables at all.

You need the sort of APIs that the debugger uses to access this sort of info.

查看更多
时光不老,我们不散
4楼-- · 2020-02-10 08:41

You could get at this information using the CLR debugging API though it won't be a simple couple of lines to extract it.

查看更多
爷的心禁止访问
5楼-- · 2020-02-10 08:41

I dont think this is possible, you can get the method and its parameters by looking at the StackTrace.

System.Diagnostics.StackTrace sTrace = new System.Diagnostics.StackTrace(true);
for (Int32 frameCount = 0; frameCount < sTrace.FrameCount; frameCount++){ 
     System.Diagnostics.StackFrame sFrame = sTrace.GetFrame(frameCount);
     System.Reflection.MethodBase thisMethod = sFrame.GetMethod();
     if (thisMethod == currentMethod){
          if (frameCount + 1 <= sTrace.FrameCount){
               System.Diagnostics.StackFrame prevFrame = sTrace.GetFrame(frameCount + 1);
               System.Reflection.MethodBase prevMethod = prevFrame.GetMethod();
          }
     }
}
查看更多
我想做一个坏孩纸
6楼-- · 2020-02-10 08:41

I don't know how it's possible using reflection, but look at using weaving. SpringFramework.Net allows you to define pointcuts that can intercept method calls. Others probably do it as well.

Here's a link to the "BeforeAdvice" interceptor http://www.springframework.net/docs/1.2.0-M1/reference/html/aop.html#d0e8139

查看更多
孤傲高冷的网名
7楼-- · 2020-02-10 08:46

The folks at secondlife suspend scripts and move them between servers. That implies that they have to capture the state of a running script, including the values of variables on the call stack.

Their scripting language runs on mono, an open source implementation of the .NET runtime. I doubt that their solution applies to the regular .NET runtime, but the video of the presentation on how they did it (skip to second half) might still be interesting.

查看更多
登录 后发表回答