Reflection: FindMembers returning empty

329 Views Asked by At

I'm trying to list all members with a given attribute, I've implemented a method that uses FindMembers but it always return an empty collection. Can anyone tell me what I'm doing wrong?

public List<MemberInfo> GetMembers<TClass, TAttribute>()
{
    Type type = typeof(TClass);
    Type attributeType = typeof(TAttribute);
    List<MemberInfo> members = type.FindMembers(MemberTypes.All, BindingFlags.Default, Filter, null).ToList();
    return members;
}

public bool Filter(MemberInfo memberInfo, object filterCriteria)
{
    return memberInfo.IsDefined(typeof(TestAttribute));
}

[Test]
public string MethodName()
{
    return "test";
}

When it I call like this:

List<MemberInfo> members = GetMembers<TestClass, TestAttribute>();

It returns empty.

2

There are 2 best solutions below

2
On BEST ANSWER

From the docs, BindingFlags.Default:

Specifies that no binding flags are defined.

You need to tell FindMembers exactly what you want, for example if you want public members that are either static or instance members:

var flags = BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance;
List<MemberInfo> members = type.FindMembers(MemberTypes.All, flags, Filter, null).ToList();

As an aside, you may want to add a generic type constraint to your GetMember function to restrict the attribute type:

public List<MemberInfo> GetMember<TClass, TAttribute>() 
    where TAttribute : Attribute
1
On

You can also use GetMembers() method and then filter your result:

var members = type.GetMembers().Where(x => Attribute.IsDefined(x, typeof(TestAttribute))).ToList()