2010-06-11 43 views
10

有人可以給我一個使用Attribute.isDefined()來檢查一個特定的自定義屬性是否已經應用於給定類的例子嗎?C#Attribute.isDefined()示例?

我已經檢查了msdn,但只能看到應用於程序集,成員等的屬性的可能性。我也開放給實現相同事物的替代方法!

回答

6

一個簡單的例子:

using System; 
using System.Diagnostics; 

[Foo] 
class Program { 
    static void Main(string[] args) { 
     var t = typeof(Program); 
     var ok = Attribute.IsDefined(typeof(Program), typeof(FooAttribute)); 
     Debug.Assert(ok); 
    } 
} 

class FooAttribute : Attribute { } 
+0

這是檢查一個成員 - 一個類的屬性呢?也許同樣的作品? – UpTheCreek 2010-06-11 20:16:36

+2

它非常*不直觀,Type類繼承MemberInfo。所以IsDefined(MemberInfo,Type)重載完成了工作。代碼片段已更新。 – 2010-06-11 21:56:38

+0

啊,我明白了,謝謝! – UpTheCreek 2010-06-12 10:13:27

2

似乎沒有 Attribute.IsDefined的超負荷,需要 Type

相反, 你可以打電話Type.GetCustomAttributes

if (typeof(SomeClass).GetCustomAttributes(typeof(SomeAttribute), false).Length > 0) 
+0

感謝。我想知道爲什麼沒有超載?我希望使用屬性更清潔一些。使用標記接口是很誘人的(SomeClass是SomeMarkerInterface)。 – UpTheCreek 2010-06-11 20:15:20

+1

There *有*重載,IsDefined(MemberInfo,Type)完成工作。我也驚訝於我:) – 2010-06-11 21:59:50

1

Type class繼承MemberInfo
因此,您可以使用,需要一個MemberInfooverload

if (Attribute.IsDefined(typeof(SomeClass), typeof(SomeAttribute)) 
+0

啊,謝謝你的眼睛比涉及長度更好:) – UpTheCreek 2010-06-12 10:15:07