使用IsDefined而不是GetCustomAttributes有什么好处

考虑一个程序集包含一个或多个属于自定义属性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; 

使用这两种方法进行快速测试,似乎IsDefinedGetCustomAttributes快得多

200000次迭代

 IsDefined average Ticks = 54 GetCustomAttributes average Ticks = 114 

希望这可以帮助 :)

正如萨达姆演示的那样, IsDefinedGetCustomAttributes更有效。 这是可以预料的。

如此处所述 ,将属性MyAttribute应用于类MyClass在概念上等同于创建MyAttribute实例。 但是,实例化实际上并不会发生,除非像GetCustomAttributes一样查询MyClass属性。

另一方面, IsDefined不会实例化MyAttribute