Assuming the following hypothetical inheritance hierarchy:
public interface IA
{
int ID { get; set; }
}
public interface IB : IA
{
string Name { get; set; }
}
Using reflection and making the following call:
typeof(IB).GetProperties(BindingFlags.Public | BindingFlags.Instance)
will only yield the properties of interface IB
, which is "Name
".
If we were to do a similar test on the following code,
public abstract class A
{
public int ID { get; set; }
}
public class B : A
{
public string Name { get; set; }
}
the call typeof(B).GetProperties(BindingFlags.Public | BindingFlags.Instance)
will return an array of PropertyInfo
objects for "ID
" and "Name
".
Is there an easy way to find all the properties in the inheritance hierarchy for interfaces as in the first example?
Responding to @douglas and @user3524983, the following should answer the OP's question:
or, for an individual property:
OK next time I'll debug it before posting instead of after :-)
this worked nicely and tersely for me in a custom MVC model binder. Should be able to extrapolate to any reflection scenario though. Still kind of stinks that it's too pass
I've tweaked @Marc Gravel's example code into a useful extension method encapsulates both classes and interfaces. It also add's the interface properties first which I believe is the expected behaviour.
Type.GetInterfaces
returns the flattened hierarchy, so there is no need for a recursive descent.The entire method can be written much more concisely using LINQ:
Interface hierarchies are a pain - they don't really "inherit" as such, since you can have multiple "parents" (for want of a better term).
"Flattening" (again, not quite the right term) the hierarchy might involve checking for all the interfaces that the interface implements and working from there...
Exactly the same problem has a workaround described here.
FlattenHierarchy doesnt work btw. (only on static vars. says so in intellisense)
Workaround. Beware of duplicates.