考虑一个程序集包含一个或多个属于自定义属性的类型的情况,MyAttribute您需要获取这些类型的列表.除了更紧凑的语法之外,使用IsDefined与GetCustomAttributes有什么好处?是否暴露/隐藏了另一个没有的东西?一个比另一个更有效吗?
以下是演示每种用法的代码示例:
Assembly assembly = ...
var typesWithMyAttributeFromIsDefined =
from type in assembly.GetTypes()
where type.IsDefined(typeof(MyAttribute), false)
select type;
var typesWithMyAttributeFromGetCustomAttributes =
from type in assembly.GetTypes()
let attributes = type.GetCustomAttributes(typeof(MyAttribute), false)
where attributes != null && attributes.Length > 0
select type;
Run Code Online (Sandbox Code Playgroud)