【发布时间】:2013-02-05 23:47:40
【问题描述】:
考虑一个程序集包含一个或多个类型的情况,该类型具有自定义属性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;
【问题讨论】:
-
这需要大量的类来明确地回答这个问题,但是是的,在返回 bool 的方法和返回新数组(单数
GetCustomAttribute通过GetCustomAttributes)。查看代码,成本似乎比这种差异更重要,但与往常一样,您应该分析以确定这是否是您关心的差异。
标签: c# reflection attributes