过IsDefined一个GetCustomAttributes受

过IsDefined一个GetCustomAttributes受

本文介绍了有没有使用过IsDefined一个GetCustomAttributes受益的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在那里组装包含自定义属性 MyAttribute 归咎于一个或多个类型,你需要得到这些类型的列表考虑这样的情况。是否有使用与 GetCustomAttributes 中除了更紧凑的语法?做一件揭露/隐藏的东西,其他的不?是其中一个比另一个更有效?

下面是code样品展示每个用法:

 装配装配= ...
VAR typesWithMyAttributeFromIsDefined =
        从类型assembly.GetTypes()
        其中,type.IsDefined(typeof运算(MyAttribute),FALSE)
        选择类型;VAR typesWithMyAttributeFromGetCustomAttributes =
        从类型assembly.GetTypes()
        让属性= type.GetCustomAttributes(typeof运算(MyAttribute),FALSE)
        其中,属性= NULL&放大器;!&安培; attributes.Length> 0
        选择类型;


解决方案

完成快速测试的两种方法,它似乎 IsDefined 是一个很大的速度比 GetCustomAttributes

20万次迭代

  IsDefined平均蜱= 54
GetCustomAttributes平均蜱= 114

希望这有助于:)

Consider the case where an assembly contains one or more types attributed with a custom attribute MyAttribute and you need to get a list of these types. Is there any benefit of using IsDefined vs. GetCustomAttributes aside from the more compact syntax? Does one expose/hide something that the other doesn't? Is one more efficient than the other?

Here is a code sample demonstrating each usage:

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;
解决方案

Done a quick test with the two methods and it seems IsDefined is a lot faster than GetCustomAttributes

200000 iterations

IsDefined average Ticks = 54
GetCustomAttributes average Ticks = 114

Hope this helps :)

这篇关于有没有使用过IsDefined一个GetCustomAttributes受益的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 20:00