2016-10-26 80 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作爲АлександрЛысенко建議它似乎是你在找什麼:如果一個或多個

返回true attributeType或其任何派生類型的實例應用於此成員;否則,是錯誤的。

相關問題