How to exclude father class properties

Suppose I have the following two classes.

public class Father { public int Id { get; set; } public int Price { get; set; } } public class Child: Father { public string Name { get; set; } } 

How can I find out if a particular property is a property of the Father (Inherited) or a child?

I tried

 var childProperties = typeof(Child).GetProperties().Except(typeof(Father).GetProperties()); 

but it seems, moreover, that it does not reveal the equality of the properties of the Father and the children of inherited properties.

+7
reflection c # system.reflection
source share
4 answers

Just try it like this:

 var childPropertiesOnly = typeof(Child) .GetProperties() .Where(x => x.DeclaringType != typeof(Father)) .ToList(); 
+7
source share

Use the GetProperties overload, which accepts BindingFlags . Turn on the DeclaredOnly flag next to the Public and Instance flags, and you are all set:

 var childProperties = typeof(Child) .GetProperties( BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly // to search only the properties declared on // the Type, not properties that // were simply inherited. ); 

This will return one property, Name.

exclude inherited debug properties

Please note that with this solution you do not need to check for DeclaringType.

+7
source share

Inspect the DeclaringType property on PropertyInfo . This should tell you enough information.

+5
source share

If you only want properties that are defined by the class but not inherited, you can pass the BindingFlags.DeclaredOnly binding BindingFlags.DeclaredOnly to the GetProperties method.

Ref: https://msdn.microsoft.com/en-us/library/system.reflection.bindingflags(v=vs.110).aspx

Change 1:
Thanks to Rene for pointing out that this is not a working answer yet.
In fact, I often forget to pass these required bind flags to GetXXX methods.
And the program will always work as expected ...

In any case, in order to make this method work, you must always specify 1) the visibility / accessibility (i.e., public or not) and 2) the area (static / instance) of the required members.
If you do not, the GetXXX return value will be empty (or an empty array, I'm not quite sure about this, but you will get an idea.)

In conclusion, so that everything is correct, you could:
1. Select BindingFlags.Public or BindingFlags.NonPublic or both.
2. Select BindingFlags.Instance or BidningFlags.Static or both.
3. Combine the selected flags with the previous steps using BindingFlags.DeclaredOnly

So, in your case, the result will be the string specified in the Rene answer.
(I need to edit the answer, because it seems that I still can not comment ...)

+1
source share

All Articles