Search code examples
c#reflectiontypesattributesmemberinfo

Reflection: FindMembers returning empty


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.


Solution

  • 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