1

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.

Matheus Simon
  • 668
  • 11
  • 34

2 Answers2

2

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
DavidG
  • 113,891
  • 12
  • 217
  • 223
1

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

var members = type.GetMembers().Where(x => Attribute.IsDefined(x, typeof(TestAttribute))).ToList()
yolo sora
  • 434
  • 5
  • 17