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

前端 未结 4 677
长情又很酷
长情又很酷 2020-12-25 09:27
class Parent {
   public string A { get; set; }
}

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

I need to get only property B, without

相关标签:
4条回答
  • 2020-12-25 09:45

    Add BindingFlags.DeclaredOnly

    0 讨论(0)
  • 2020-12-25 09:45

    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;
    
    0 讨论(0)
  • 2020-12-25 09:52

    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)
    
    0 讨论(0)
  • 2020-12-25 09:56

    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);
    
    0 讨论(0)
提交回复
热议问题