简体   繁体   English

从FieldInfo获取容器类实例

[英]Get a container class instance from a FieldInfo

I am working with C# reflection here: I have a FieldInfo of a property and I would like to get the instance of the class it belong (so I can reach the content of another property): 我在这里使用C#反射:我有一个属性的FieldInfo,我想获取它所属的类的实例(以便可以到达另一个属性的内容):

for exemple take this class: 例如参加本课程:

class MyClass
{
   public int A { get; set; }
   public int B { get; set; }
}

in some part of the code I have 在部分代码中

void Function(FieldInfo fieldInfoOfA)
{
  // here I need to find the value of B
}

Is this possible ? 这可能吗 ?

FieldInfo provides access to the metadata for a field within a class, it is independent of a specified instance. FieldInfo提供对类中字段的元数据的访问,它独立于指定的实例。

If you have an instance of MyClass you can do this: 如果您有MyClass的实例,则可以执行以下操作:

object Function(MyClass obj, FieldInfo fieldInfoOfA)
{
    var declaringType = fieldInfoOfA.DeclaringType;

    var fieldInfoOfB = declaringType.GetField("B");

    return fieldInfoOfB.GetValue(obj);
}

Is this possible ? 这可能吗 ?

No. Reflection is about discovery of the metadata of a type. 否。反射与发现类型的元数据有关。 A FieldInfo does not contain any information about a particular instance of that type. FieldInfo不包含有关该类型的特定实例的任何信息。 This is why you can get a FieldInfo without even creating an instance of the type at all: 这就是为什么即使根本不创建该类型的实例也可以获取FieldInfo原因:

typeof(MyClass).GetField(...)

Given the snippet above, you can see that a FieldInfo can be obtained without any dependence on a particular instance. 在上面的代码段中,您可以看到可以获得FieldInfo而不依赖于特定实例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM