开发者

Get by reflection properties of class ,but not from inherited class

开发者 https://www.devze.com 2023-04-09 01:28 出处:网络
class Parent { public string A { get; set; } } class Child : Parent { public string B { get; set; } } I need to get only property B, without property A
class Parent {
   public string A { get; set; }
}

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

I need to get only property B, without property A but

开发者_如何学Go
Child.GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance)

return both properties :/


You should add BindingFlags.DeclaredOnly to your flags, i.e:

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


Try using the DeclaredOnly binding flag. It should limit the properties returned to only those declared on the class you are interested in. And here is a code sample:

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


From Type.cs : In this case use the 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;


Add BindingFlags.DeclaredOnly

0

精彩评论

暂无评论...
验证码 换一张
取 消