netmajor netmajor - 1 year ago 35
C# Question

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

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

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


return both properties :/

Answer Source

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)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download