Capturing method state using Reflection

2020-02-10 08:44发布

问题:

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

回答1:

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



回答2:

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:

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:

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();
          }
     }
}


回答5:

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



回答6:

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.