[英]Get own property name from parent class using reflection
Is is possible to get the name of property that the current class is assigned to in the class it was called from? 是否可以获取当前类在其调用的类中分配的属性名称?
Let's say I've got 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'd like to Log
the value myName
when the Method
is called from Parent1
and mySecondName
if the Method
is called from Parent2
. 我想
Log
值myName
时, Method
是从所谓的Parent1
和mySecondName
如果Method
是从所谓的Parent2
。
Is it possible using reflection and not by passing names by string in argument (I want to use it only for the debugging purposes, I don't want to link those class together in any way) 是否可以使用反射而不是通过参数中的字符串传递名称(我只想将其用于调试目的,我不想以任何方式将这些类链接在一起)
Using the StackTrace
you can at least get the method and class from which the call was made: 使用
StackTrace
您至少可以获取进行调用的方法和类:
System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace();
Type calledFromType = trace.GetFrame(1).GetMethod().ReflectedType;
This should give you the Parent1
type. 这应该给你
Parent1
类型。
I don't think there is a way to get the name of the variable with which the method was invoked. 我认为没有办法获取调用该方法的变量的名称。
You could of course enumerate all fields and properties of calledFromType
and see if one of them is of the Child
type, but you won't get a guarantee that field or property was actually used when invoking. 您当然可以枚举
calledFromType
所有字段和属性,并查看其中一个是否属于Child
类型,但是您无法保证在调用时实际使用了字段或属性。
There is no realistic way to do this using reflection, for a variety of reasons: 由于各种原因,使用反射没有现实的方法来做到这一点:
There is nothing in the state of your instance that is related to a specific 'owner'. 您的实例状态中没有任何内容与特定的“所有者”相关。
Your code can be called from anywhere that has access to the property, so a stack trace won't reliably return anything useful. 您可以从有权访问该属性的任何地方调用您的代码,因此堆栈跟踪将无法可靠地返回任何有用的内容。
A reference to your class' instance can be stored in any number of places, including variables and parameters to method calls. 对类实例的引用可以存储在任意数量的位置,包括方法调用的变量和参数。
So basically, no. 所以基本上没有。 The best you can do is tell it where it is, and even then you fall foul of reference copies.
你能做的最好的事情是告诉它它在哪里,即使这样,你也会违反参考文献。
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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.