2016-10-26 3 views
2

を持っている:ないオブジェクトクラスを指定された属性

[ProtoContract] 
[Serializable] 
public class TestClass 
{ 
    [ProtoMember(1)] 
    public string SomeValue { get; set; } 
} 

と方法:

public static void Set(object objectToCache) 
{ 

} 

objectToCacheが属性ProtoContractを持っているかどうかを確認することが可能ですか?

+0

'objectToCache.GetTypeを()GetCustomAttributes()'またはそのバリエーション。 –

答えて

2

最も簡単な方法は、以下のコードを使用することである:。

public static void Set(object objectToCache) 
{ 
    Console.WriteLine(objectToCache.GetType().IsDefined(typeof(MyAttribute), true)); 
} 
+0

ニースの答えは、それについて考えなかった:)私のupvoteを得た –

1

はい:

var attributes = TestClass.GetType().GetCustomAttributes(typeof(ProtoContract), true); 
if(attributes.Length < 1) 
    return; //we don't have the attribute 
var attribute = attributes[0] as ProtoContract; 
if(attribute != null) 
{ 
    //access the attribute as needed 
} 
1

使用GetCustomAttributes指定されたオブジェクトが持つ属性のコレクションを返します。いずれかのご希望のタイプ

public static void Main(string[] args) 
{ 
    Set(new TestClass()); 
} 

public static void Set(object objectToCache) 
{ 
    var result = objectToCache.GetType().GetCustomAttributes(false) 
             .Any(att => att is ProtoContractAttribute); 

    // Or other overload: 
    var result2 = objectToCache.GetType().GetCustomAttributes(typeof(ProtoContractAttribute), false).Any(); 
    // result - true 
} 

АлександрЛысенкоが、あなたが探しているもののように見えるん示唆したようIsDefinedについての詳細を読んでいるなら、チェックします。

戻り値を真の一つ以上の場合attributeTypeのインスタンスまたはその派生型のいずれかがこのメンバに適用されます。それ以外の場合はfalseです。

関連する問題