2010-03-04 121 views
4

我讀了關於屬性和理解,他們可以進行以適用於不同的目標實體與你的代碼 - (見Attribute Targets)。C#屬性和屬性定位/目標

所以,看着的AssemblyInfo.cs文件在我的項目,我可以看到以下內容:

[assembly: AssemblyTitle("AttributesDemo")] 
[assembly: AssemblyDescription("")] 

這對我來說很有意義。目標是程序集的屬性。

在我的代碼,我可以如下類上添加一個屬性:

[MyAttribute] 
class MySerialzableClass 
{ 

隨着MyAttribute之中:

[AttributeUsage (AttributeTargets.All)] 
public class MyAttribute : System.Attribute 
{ 
} 

所以,我在第一碼思考assembly:聲明塊。而且試過,只是實驗:

[class: MyAttribute] 
class MySerialzableClass 
{ 

這使編譯器警告:

「類」是無法識別的屬性 位置。該塊 中的所有屬性都將被忽略。

所以我的問題是這樣的 - 爲什麼必須在某些屬性上指定屬性目標並且不需要或不允許其他人使用?此外,你必須做到這一點?

回答

5

如果目標未在代碼中表示,您必須明確指定目標。我知道只有三個目標,裝配,模塊和回報:

[return: MyAttribute] 
public static int meth(

類指定類:過多時,編譯器能明白你的意思

+0

+1提*其他*例外。 – 2010-03-04 16:12:56

+0

+1並接受答案,雖然不應該是'ReturnValue:',而不是'Return:' – 2010-03-05 16:13:19

+0

否:)只需編寫並嘗試編譯即可。 – Andrey 2010-03-05 16:21:43

3

正常情況下,屬性會在其影響之前發生,如類或方法。對於程序集範圍的屬性,沒有「之前」,所以你必須指定。

4

您可以爲任何屬性使用指定attribute targets,但只那些沒有默認值的(assemblymodule)是強制性的。此外,如果您要將屬性應用於非默認目標,則您必須使用這些註釋。非默認目標

例子:

[return: MyAttribute] 
public int Method() { ... } 

public int Property { 
    get; 
    [param: MyAttribute] // applies to the parameter to the setter 
    set; 
} 

在你的榜樣,正確的目標(這是默認值)是type

[type: MyAttribute] 
class MySerialzableClass { } 
+1

這是最好的答案,因爲它提供了正確的目標關鍵字'type:'。可能的全局目標是'assembly'和'module',非全局目標是'field','event','method','param','property','return'和'type'。 – 2013-06-30 22:04:40