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

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

所以如果我有课

[Findable] public class MyFindableClass {} 

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

我可以用一个很大的邪恶黑客做到这一点,但我确信有人有更好的方式。

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

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

编辑:根据Marc Gravell的建议从MemberInfo.GetCustomAttributes移动到Attribute.IsDefined