通过类的反射属性获取,但不能从继承的类获取


80
class Parent {
   public string A { get; set; }
}

class Child : Parent {
   public string B { get; set; }
}

我只需要获得属性B,而无需获得属性A,但是

Child.GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance)

返回两个属性:/

Answers:



10

尝试使用DeclaredOnly绑定标志。它应该将返回的属性限制为仅对您感兴趣的类声明的属性。这是一个代码示例:

PropertyInfo[] properties = typeof(Child).GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.DeclaredOnly);


4

来自Type.cs :在这种情况下,使用DeclaredOnlyLookup

  private const BindingFlags DefaultLookup = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public;
  internal const BindingFlags DeclaredOnlyLookup = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly;

1
有趣的是,我将使用这种方法并定义自己的const BindingFlags。+1用于查看源代码。
C. Tewalt '16
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.