8

カスタム属性で属性付けされた 1 つ以上の型がアセンブリに含まれており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;
4

2 に答える 2

12

2つの方法で簡単なテストを行ったところIsDefinedGetCustomAttributes

200000回の繰り返し

IsDefined average Ticks = 54
GetCustomAttributes average Ticks = 114

お役に立てれば :)

于 2013-02-06T00:51:55.787 に答える