Reputation: 12584
I know that there are many questions like this, but I couldn't find any answer to what I'm trying to do.
Considering the following abstract class:
public abstract class TestBase
{
public static ITest Test => Container.Resolve<ITest>();
public static ITest1 Test1 => Container.Resolve<ITest1>();
public static ITest2 Test2 => Container.Resolve<ITest2>();
public static ITest3 Test3 => Container.Resolve<ITest3>();
}
I'm trying to get all the properties that inherit from an interface IDummy like this:
var members = typeof(TestBase).GetMembers(BindingFlags.Static | BindingFlags.Public)
.Where(f => f.GetType().IsAssignableFrom(typeof(IDummy)) == true);
but the list is empty. Without adding the where clause ".Where(f => f.GetType().IsAssignableFrom(typeof(IDummy)) == true)
" I get all the results including the getters for the properties.
Probably is something trivial, but as I'm not so familiar with reflection I can't figure out what I'm doing wrong.
Upvotes: 3
Views: 2138
Reputation: 20770
What you get back from GetMembers
is MemberInfo
instances (or, for fields, FieldInfo
instances). Hence, you cannot check these objects directly for being assignable from IDummy
.
What you actually want to do is filter the MemberInfo
objects for fields, then check the FieldType
property of each of these objects:
var members = typeof(TestBase).GetMembers(BindingFlags.Static | BindingFlags.Public)
.OfType<FieldInfo>()
.Where(f => typeof(IDummy).IsAssignableFrom(f.FieldType));
Also, note that I turned around the subject and object of the IsAssignableFrom
call, as also suggested in Patrick's comment.
As I just noticed, your example seems to show properties rather than fields. The general technique is the same, though; just use PropertyInfo
and PropertyType
rather than FieldInfo
and FieldType
, respectively.
Lastly, rather than filtering for PropertyInfo
yourself, you could also use the one of the overloads of the GetProperties
method directly.
Upvotes: 7