Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the values of the parameters of a calling method?

Tags:

Question

I'm writing some code that needs to be able to get the values of the parameters from the method that called into the class. I know how to get all the way to the ParameterInfo[] array, but I don't know how to then get the values. Is this even possible?

If it is, I think it has something to do with using the MethodBody property from the MethodInfo object, which allows you to inspect the IL stream, including properties, but I don't know how to do it, and I haven't found applicable code on Google.

Code

// Finds calling method from class that called into this one public class SomeClass {     public static void FindMethod()     {         for (int i = 1; i < frameCount; i++)         {             var frame = new StackFrame(i);             var methodInfo = frame.GetMethod();             if (methodInfo.DeclaringType != this.GetType())             {                 string methodName = frame.GetMethod().Name;                 var paramInfos = methodInfo.GetParameters();                  // Now what?? How do I get the values from the paramInfos                  break;             }             else if (i == frameCount - 1)             {                 throw new TransportException("Couldn't find method name");             }         }     } } 
like image 770
Chris Benard Avatar asked Jan 29 '09 17:01

Chris Benard


1 Answers

You cannot do it without introspecting the stack yourself (and this is fragile since many optimizations may mean the stack frame is not what you expect, or even that the parameter passed is not in fact what the method signature would suggest (it is perfectly possible for an optimizing JIT compiler to spot that you are only using a sub field of an object/struct and pass that instead).

The ParameterInfo simply tells you the signature of the method as compiled, not the values that were passed.

The only realistic way to achieve this automatically is via code injection (via something like AOP) to create the data and do what you want with it based on analysing the IL.

This is generally not a good idea, if you need to debug something use a debugger, if you need to log something be explicit about what you are logging.

To be clear simple reflective techniques cannot achieve what you desire with full generality

like image 108
ShuggyCoUk Avatar answered Oct 01 '22 01:10

ShuggyCoUk