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.
From the docs,
BindingFlags.Default
:You need to tell
FindMembers
exactly what you want, for example if you want public members that are either static or instance members:As an aside, you may want to add a generic type constraint to your
GetMember
function to restrict the attribute type: