如何在运行时使用反射从 class 的对象获取 属性 的值

How to get value of property from object of class at runtime using reflection

我有一个 class 如下所示:

Class A : B<C>
{
    public A(C entity):base(entity)
    {}
}

abstract class B<T>
{
    public B(T entity)
        {
            Entity = entity;
        }

        public T Entity { get; private set; }
}

Class C: D
{
    public string prop2{get;set;}
}
Class D
{
    public string prop1{get;set;}
}
 Main()
 {
 A obj = new A(new C());
 obj.GetType().GetProperty("prop1",  BindingsFlag.Instance|BindingsFlag.FlatteredHierarchy)//  is null


 }

我有对象class A。 我想在运行时从此对象获取 属性 值。

我正在尝试

obj.GetType().GetProprty("propertyName", 
                         BindingsFlag.FlattenHierarchy).GetValue(obj, null);

但是 GetProprty() 返回空值,因为 属性 在 D 或 C class 中声明。

有人可以建议我如何实现吗?

提前致谢。

GetType().GetProperty("propertyName", BindingsFlag.FlattenHierarchy)
         .GetValue(obj, null);

您缺少指定是获取实例还是静态的绑定标志 属性:

 BindingsFlag.FlattenHierarchy | BindingsFlag.Instance

根据 MSDN 标志 BindingsFlag.InstanceBindingsFlag.Static 必须明确指定才能获得非空值:

You must specify either BindingFlags.Instance or BindingFlags.Static in order to get a return.

此外,public 属性在默认情况下被排除在外。所以如果你 属性 是 public 你需要指定额外的标志:

BindingsFlag.FlattenHierarchy | BindingsFlag.Instance | BindingsFlag.Public

备注:

Specify BindingFlags.Public to include public properties in the search.

如果base中的属性是私有的,FlattenHierarchy将不会枚举它:

(...) private static members in inherited classes are not included If this is your case, I am afraid that you have to manually travel through base class and search for that property.

还要确保 属性 名称有效且存在。

编辑: 编辑后,我看到了问题。 你的 class A 不是 D class 的子class(你想从 D class 得到 属性)。 这就是为什么无法以这种方式获取 属性 值。 您需要按照以下步骤操作:

// get entity prop value
var entityValue =
    (obj.GetType()
        .GetProperty("Entity", 
           BindingFlags.FlattenHierarchy | BindingFlags.Instance | BindingFlags.Public)
        .GetValue(obj));
// get prop value
var prop1Value =
    entityValue.GetType()
               .GetProperty("prop1", 
                  BindingFlags.FlattenHierarchy | 
                  BindingFlags.Instance | 
                  BindingFlags.Public)
               .GetValue(entityValue);

记得处理 null 值等