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.GetCustomAttributes到Attribute.IsDefined基于马克Gravell的建议.