明示屬性目標 (C# 程式設計手冊)

更新:2007 年 11 月

在某些情況下,屬性的目標 (亦即屬性所套用的實體),似乎模稜兩可。例如,在以下的方法宣告中,SomeAttr 屬性可套用至方法或者是方法的傳回值:

public class SomeAttr : System.Attribute { }

[SomeAttr]
int Method()
{
    return 0;
}

當封送處理時經常發生這種情況。若要解決這種模稜兩可的情況,C# 每一種宣告都擁有一套預設的目標,可藉由明確指定屬性目標來覆寫預設的目標。

// default: applies to method
[SomeAttr]
int Method1() { return 0; } 

// applies to method
[method: SomeAttr]
int Method2() { return 0; } 

// applies to return value
[return: SomeAttr]
int Method3() { return 0; } 

請注意,這與將 SomeAttr 定義為有效的目標無關,也就是說,即使將 SomeAttr 定義為只套用至傳回值,仍然必須指定 return 目標。換句話說,編譯器將不會使用 AttributeUsage 資訊來解析模稜兩可的屬性目標。如需詳細資訊,請參閱 AttributeUsage (C# 程式設計手冊)

屬性目標的語法如下所述:

[target : attribute-list]

參數

  • target
    以下其中一項:組件、欄位、事件、方法、模組、參數、屬性、傳回、型別。

  • attribute-list
    適用屬性的清單。

下表列出允許使用屬性的所有宣告;第二欄中列出宣告的屬性可能的目標。粗體字者為預設屬性。

宣告

可能的目標

assembly

assembly

module

module

class

type

struct

type

interface

type

enum

type

delegate

type、return

method

method、return

parameter

param

Field

field

property — indexer

property

property — get accessor

method、return

property — set accessor

method、param、return

event — field

event、field、method

event — property

event、property

event — add

method、param

event — remove

method、param

組件與模組層級的屬性並沒有預設目標。如需詳細資訊,請參閱全域屬性

範例

using System.Runtime.InteropServices;
[Guid("12345678-1234-1234-1234-123456789abc"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
interface ISampleInterface
{
    [DispId(17)]  // set the DISPID of the method
    [return: MarshalAs(UnmanagedType.Interface)]  // set the marshaling on the return type
    object DoWork();
}

請參閱

概念

C# 程式設計手冊

參考

反映 (C# 程式設計手冊)

屬性 (C# 程式設計手冊)

使用屬性 (C# 程式設計手冊)

建立自訂屬性 (C# 程式設計手冊)

使用反映存取屬性 (C# 程式設計手冊)

System.Reflection

Attribute