简体   繁体   English

.NET FieldInfo - 获取* *是*字段的对象

[英].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? 如何以编程方式获取对FieldInfo对象为字段的对象的引用?

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. FieldInfo对象表示独立于任何实例的元数据。 There is 1 FieldInfo for every instance of an object's field. 对象字段的每个实例都有1个FieldInfo。

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. 一般而言,所有元数据对象(如Type,FieldInfo,MethodInfo等)都是如此......可以使用元数据对象来操作对象的实例。 For instance FieldInfo can be used to grab an instance value via the GetValue method. 例如,FieldInfo可用于通过GetValue方法获取实例值。

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

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

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