简体   繁体   中英

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):

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.

If you have an instance of MyClass you can do this:

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. This is why you can get a FieldInfo without even creating an instance of the type at all:

typeof(MyClass).GetField(...)

Given the snippet above, you can see that a FieldInfo can be obtained without any dependence on a particular instance.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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