jeudi 24 septembre 2020

c#: How to get the value of 'this' with Reflection?

Is there a way to find out the value of the implicit this parameter which is passed into a function a few stack frames above the current code? I know this sounds weird, so let me give you the bigger picture.

I am working with a framework for test automation that lets me plug in my own code in a separate .NET assembly. My code is a public static method which eventually gets called by the framework. From the way the framework works I know that my code is indirectly called by a Run method. Run is a non-static method of a class that implements the ITestModule interface.

My code wants to access a non-static property in the instance whose Run method is executing, or in other words, a property member of the implicit this of the Run method.

The code I wrote so far uses the StackTrace class to traverse the stack and asks each stack frame whether its method has the signature which I expect. Once it find a match, the code asks the method's ReflectedType for the underlying class from which it gets a PropertyInfo for the requested property. If now I had this as well, I could go ahead and call MethodInfo.GetMethod.Invoke to retrieve the property value.

This is the code, omitting error checking etc.

StackTrace st = new StackTrace();
for (int j = 0; j < st.FrameCount; ++j)
{
  // examine each stack frame until we find what we are looking for
  StackFrame frame = st.GetFrame(j);
  MethodBase method = frame.GetMethod(); // executing method
  if (method.ToString() == "<method signature>")
  {
    // We have found the "Run" method
    Type rType = method.ReflectedType; // class of which "Run" is a member
    PropertyInfo pInfo = rType.GetProperty(property_name); // the property
    MethodInfo propGet = pInfo.GetMethod; // the property's "get" accessor

    Object instance = ...; // The "this" of the "Run" method
    Object result = propGet.Invoke(instance, null); // Retrieve the property value
    // do something with result

    break;
  }
}

It is the Object instance = ...; line that gives me headache.

Thanks a lot for any suggestions.

Hans





Aucun commentaire:

Enregistrer un commentaire