使用自定义属性获取程序集中的所有类型

Aid*_*dan 26 c# reflection custom-attributes

是否有一种优雅的方法来获取具有自定义属性的程序集中的所有类型?

所以如果我有课

[Findable]
public class MyFindableClass
{}
Run Code Online (Sandbox Code Playgroud)

我希望能够在Assembly.GetTypes(...)返回的类型集合中找到它.

我可以用一个卑鄙的黑客来做,但我确信有人有更好的方式.

Ani*_*Ani 45

我不认为你可以避免枚举程序集中的每个类型,检查属性,但你可以使用LINQ使查询更容易理解:

Assembly assembly = ...
var types = from type in assembly.GetTypes()
            where Attribute.IsDefined(type, typeof(FindableAttribute))
            select type;
Run Code Online (Sandbox Code Playgroud)

编辑:从感动MemberInfo.GetCustomAttributesAttribute.IsDefined基于马克Gravell的建议.

  • 严格地说,Attribute.IsDefined(type,attribType)在这里会更有效 (4认同)
  • 可能是type.IsDefined(attribType) - 在这种情况下,我的错误http://msdn.microsoft.com/en-us/library/system.reflection.memberinfo.isdefined.aspx (2认同)