具有适当BindingFlags的继承/子类的GetProperties不返回预期的属性

时间:2016-09-14 00:53:05

标签: c# asp.net-core

我确实关注了以下帖子'建议

  1. Reflecting over all properties of an interface, including inherited ones?
  2. How do you get the all properties of a class and its base classes (up the hierarchy) with Reflection? (C#)
  3. Using GetProperties() with BindingFlags.DeclaredOnly in .NET Reflection
  4. 并修改我的测试以包括如下所示的绑定标志。

    目标:  我的最终目标是测试检索到的属性是否为readOnly

    问题:  ChildClass / Inherited类属性甚至不会出现在反射上。

    测试以检查属性exists - fails

    On GetProperties(BindingFlags.FlattenHiearchy)只返回一个Result属性,即父类的属性

    //My failing test
    Assert.NotNull(typeof(ChildClass).GetProperty("Id",BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly));
    
    //My Alternate version which still fails
    Assert.NotNull(typeof(ChildClass).GetProperty("Id",BindingFlags.FlattenHierarchy));
    
    // My class structure against which my test is running.
    class ChildClass:BaseClass<MyCustomObject>
    {
       public ChildClass (Guid id)
        {
            Id = id;
        }
    
        public readonly Guid Id;
    }
    
    class BaseClass<T>:IMyInterFace<T>
    {
         public T Result { get; private set; }
    }
    
    public interface IMyInterFace<T>
    {
        T Result { get; }
    
    }
    

    编辑 2016年9月14日 我道歉我错过了一个事实,即我确实知道或理解我可以Assert.NotNull如果我说GetField - 但这不会帮助我实现最终目标 - 检查它是否readonly - 我现在不确定这是否可能有人确认?谢谢!。

1 个答案:

答案 0 :(得分:2)

public readonly Guid Id字段,而不是属性。改为使用GetField方法:

typeof(ChildClass).GetField("Id", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly);

您可以查看readonly类的IsInitOnly属性来检查它是否为FieldInfo

var result = typeof(ChildClass).GetField("Id", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly);
Assert.IsTrue(result.IsInitOnly);