I believe I've got an interesting question there, since I couldn't find a clue about that during my research.
public interface IClass
{
int i { get; set; }
}
public class A
{
int j { get; set; }
}
public class B : A, IClass
{
string property { get; set; }
}
I would like to know if it is possible, using Reflection, to get all the inherited members of my class B and from the inherited interface IClass, but without the property from the inherited class A.
I've tried using BindingFlags.DeclaredOnly, but this always gets all the inherited members, when I only desire to get the ones from the Interface.
Any ideas, please ?
-- Arjune
EDIT : I intend to get interface inherited properties, with a generic class T. Here is what I tried which worked, thanks to your answers :
List<PropertyInfo> properties = typeof(T).GetProperties(BindingFlags.FlattenHierarchy | BindingFlags.Instance | BindingFlags.Public).Where(x => x.DeclaringType != typeof(T).BaseType).ToList();
Besides the properties of B, this allowed me to get the properties from IClass but not the ones from class A. LINQ and the use of DeclaringType was the answer.
You can go about this in a number of ways, depending on your exact aim.
One idea is to get all properties normally then filter out those coming from class A
using DeclaringType
, e.g.
var typeOfA = typeof(A);
var notFromA = allMembers.Where(
p => p.DeclaringType != typeOfA && !p.DeclaringType.IsSubclassOf(typeOfA));
Or of course you can simply ignore the base class completely and get only the members coming from implemented interfaces, e.g.
var members = typeof(B).GetInterfaces().SelectMany(i => i.GetMembers());
This will give you all members of B
that are implementations of interface members -- not necessarily all of B's declared members, and it will include interface members that A
has implemented.
In general the correct way to do this depends on the exact requirements, but I feel the question is not precise enough in its current form.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With