Reputation: 1876
How can I find every occurrence of a custom attribute inside an assembly?
If can find all types from an assembly where the attribute is used but thats not enough. How about methods, properties, enum, enum values, fields etc.
Is there any shortcut for doing this or is the only way to do it to write code to search all parts of a type (properties, fields, methods etc.) ?
Reflector does this, not sure how its implemented though.
Upvotes: 3
Views: 3738
Reputation: 77546
Do,
assembly.GetTypes()
.SelectMany(type => type.GetMembers())
.Union(assembly.GetTypes())
.Where(type => Attribute.IsDefined(type, attributeType));
This will return enum
values too since those are just public static fields under the hood. Also, if you want private members, you'll have to tweak the BindingFlags
you pass in.
Upvotes: 12
Reputation: 1500515
You can use Type.GetMembers()
to get all members (properties, methods, fields etc) rather than doing each kind of member separately. That should at least make it somewhat simpler.
Note that you may well want to pass in various binding flags (instance, static, public, non-public) to make sure you catch everything.
Upvotes: 1