简体   繁体   中英

.NET FieldInfo — get the object of which it *is* a field

How does one obtain programmatically a reference to the object of which a FieldInfo object is a field?

For example, I'd like something like this:

myFieldInfo.GetOwner(); // returns the object of which myFieldObject is a field

Unfortunately you can't because the relationship works the opposite way. A FieldInfo object represents metadata that is independent of any instance. There is 1 FieldInfo for every instance of an object's field.

This is true in general about all Metadata objects such as Type, FieldInfo, MethodInfo, etc ... It is possible to use the metadata objects to manipulate an instance of an object. For instance FieldInfo can be used to grab an instance value via the GetValue method.

FieldInfo fi = GetFieldInfo();
object o = GetTheObject();
object value = fi.GetValue(o);

But a metadata object won't ever be associated with an instance of the type.

尝试这个:

myFieldInfo.DeclaringType

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