是否有一种优雅的方法可以获得具有自定义属性的程序集中的所有类型?
所以,如果我有一个班级
[Findable]
public class MyFindableClass
{}
我希望能够在Assembly.GetTypes(...)返回的类型集合中找到它
我可以用一个卑鄙的黑客来做,但我确信有人有更好的方法。
答案 0 :(得分:45)
我不认为你可以避免枚举程序集中的每个类型,检查属性,但你可以使用LINQ来使查询更容易理解:
Assembly assembly = ...
var types = from type in assembly.GetTypes()
where Attribute.IsDefined(type, typeof(FindableAttribute))
select type;
编辑:根据Marc Gravell的建议,从MemberInfo.GetCustomAttributes
移至Attribute.IsDefined
。