【问题标题】:Is there a benefit of using IsDefined over GetCustomAttributes使用 IsDefined 而不是 GetCustomAttributes 有什么好处吗
【发布时间】:2013-02-05 23:47:40
【问题描述】:

考虑一个程序集包含一个或多个类型的情况,该类型具有自定义属性MyAttribute,并且您需要获取这些类型的列表。除了更紧凑的语法之外,使用IsDefinedGetCustomAttributes 有什么好处吗?一个人是否暴露/隐藏了另一个人没有的东西?一个比另一个更有效吗?

以下是演示每种用法的代码示例:

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


【解决方案1】:

用这两种方法做了一个快速测试,似乎IsDefinedGetCustomAttributes快很多

200000 次迭代

IsDefined average Ticks = 54
GetCustomAttributes average Ticks = 114

希望这会有所帮助:)

【讨论】:

  • 然后你会记住它的滴答声并意识到它毕竟不是那么重要
【解决方案2】:

正如萨达姆所展示的,IsDefinedGetCustomAttributes 更有效率。这是意料之中的。

作为documented here,将属性MyAttribute 应用于类MyClass 在概念上等同于创建MyAttribute 实例。但是,除非像 GetCustomAttributes 那样查询 MyClass 的属性,否则实例化实际上不会发生。

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

【讨论】:

    猜你喜欢
    • 2011-12-09
    • 2012-05-18
    • 2011-10-29
    • 1970-01-01
    • 1970-01-01
    • 2020-12-22
    • 2020-08-27
    • 1970-01-01
    • 2010-09-14
    相关资源
    最近更新 更多