Get property name from parent class using reflection

Is it possible to get the name of the property to which the current class is assigned in the class from which it was called?

Let's say I have three classes:

class Parent1 { public Child myName; public void Foo() { myName.Method(); } } class Parent2 { public Child mySecondName; public void Foo() { mySecondName.Method(); } } class Child { public void Method() { Log(__propertyName__); } } 

I would like the Log value of myName when Method is called from Parent1 and mySecondName if Method is called from Parent2 .

Is it possible, using reflection, and not by passing names along the line in the argument (I want to use it only for debugging purposes, I don't want to bind this class in any way)

+4
source share
3 answers

Using StackTrace , you can at least get the method and class from which the call was made:

 System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(); Type calledFromType = trace.GetFrame(1).GetMethod().ReflectedType; 

This should give you type Parent1 .

I don’t think there is a way to get the name of the variable with which the method was called.

Of course, you could list all the fields and properties calledFromType and see if one of them is a Child type, but you won’t get the guarantee that the field or property was actually used when called.

+3
source

There is no realistic way to do this using reflection for various reasons:

  • There is nothing in the state of your instance associated with a particular "owner."

  • Your code can be called from anywhere that has access to this property, so stack tracing will not reliably return anything useful.

  • A reference to an instance of your class can be stored in any number of places, including variables and parameters for method calls.

So, in principle, no. The best you can do is tell where it is, and even then you lose reference copies.

+3
source
 class Child { public void Method() { StackFrame sf = new StackFrame(1); var type = sf.GetMethod().ReflectedType; var field = type.GetFields().FirstOrDefault(i => i.FieldType == typeof(Child)); Log(field.Name); } } 
+2
source

All Articles