Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

reflection

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 :/

like image 953
netmajor Avatar asked Sep 29 '11 10:09

netmajor


4 Answers

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)
like image 99
Francesco Baruchelli Avatar answered Nov 03 '22 12:11

Francesco Baruchelli


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);
like image 35
Petar Petkov Avatar answered Nov 03 '22 11:11

Petar Petkov


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;
like image 5
eran otzap Avatar answered Nov 03 '22 12:11

eran otzap


Add BindingFlags.DeclaredOnly

like image 4
Tigran Avatar answered Nov 03 '22 13:11

Tigran