屬性 (C#)Attributes (C#)

屬性提供一種功能強大的方法,可將中繼資料或宣告資訊關聯至程式碼 (組建、型別、方法、屬性等)。Attributes provide a powerful method of associating metadata, or declarative information, with code (assemblies, types, methods, properties, and so forth). 將屬性關聯至程式實體之後,就能在執行階段使用稱為「反映」的技術來查詢該屬性。After an attribute is associated with a program entity, the attribute can be queried at run time by using a technique called reflection. 如需詳細資訊,請參閱反映 (C#)For more information, see Reflection (C#).

屬性 (Attribute) 包含下列屬性 (Property):Attributes have the following properties:

  • 屬性會將中繼資料新增至您的程式。Attributes add metadata to your program. 「中繼資料」是在程式中定義的型別相關資訊。Metadata is information about the types defined in a program. 所有的 .NET 組件都包含一組指定的中繼資料,來描述組件中所定義的型別和型別成員。All .NET assemblies contain a specified set of metadata that describes the types and type members defined in the assembly. 您可以新增自訂屬性來指定所需的任何其他資訊。You can add custom attributes to specify any additional information that is required. 如需詳細資訊,請參閱建立自訂屬性 (C#)For more information, see, Creating Custom Attributes (C#).
  • 您可以將一或多個屬性 (Attribute) 套用至整個組件、模組或較小的程式元素,例如類別和屬性 (Property)。You can apply one or more attributes to entire assemblies, modules, or smaller program elements such as classes and properties.
  • 屬性 (Attribute) 可以利用與方法與屬性 (Property) 相同的方式來接受引數。Attributes can accept arguments in the same way as methods and properties.
  • 您的程式可以使用反映,來檢查自己的中繼資料或其他程式的中繼資料。Your program can examine its own metadata or the metadata in other programs by using reflection. 如需詳細資訊,請參閱使用反映存取屬性 (C#)For more information, see Accessing Attributes by Using Reflection (C#).

使用屬性Using attributes

屬性可以放置於大多數的任意宣告中,但特定的屬性可能會限制它適用的宣告型別。Attributes can be placed on most any declaration, though a specific attribute might restrict the types of declarations on which it is valid. 在 C# 中,指定屬性的方式是以方括弧 ([]) 括住屬性的名稱,並放置在要套用的實體宣告上方。In C#, you specify an attribute by placing the name of the attribute enclosed in square brackets ([]) above the declaration of the entity to which it applies.

在此範例中,會使用 SerializableAttribute 屬性來將特定的特性套用至類別:In this example, the SerializableAttribute attribute is used to apply a specific characteristic to a class:

public class SampleClass
    // Objects of this type can be serialized.

具有 DllImportAttribute 屬性的方法會如下範例宣告:A method with the attribute DllImportAttribute is declared like the following example:

extern static void SampleMethod();

多個屬性可以放在宣告,如下列範例所示:More than one attribute can be placed on a declaration as the following example shows:

using System.Runtime.InteropServices;
void MethodA([In][Out] ref double x) { }
void MethodB([Out][In] ref double x) { }
void MethodC([In, Out] ref double x) { }

可以針對特定實體多次指定某些屬性。Some attributes can be specified more than once for a given entity. ConditionalAttribute 就是這種多次使用屬性的一個例子:An example of such a multiuse attribute is ConditionalAttribute:

[Conditional("DEBUG"), Conditional("TEST1")]
void TraceMethod()
    // ...


依照慣例,所有的屬性名稱都會以 "Attribute" 這個字結尾,以便與 .NET 程式庫中的其他項目有所區別。By convention, all attribute names end with the word "Attribute" to distinguish them from other items in the .NET libraries. 不過,您在程式碼中使用屬性時,不需要指定屬性的後置詞。However, you do not need to specify the attribute suffix when using attributes in code. 例如,[DllImport] 相當於 [DllImportAttribute],但 DllImportAttribute 是屬性在 .NET Framework Class Library 中的實際名稱。For example, [DllImport] is equivalent to [DllImportAttribute], but DllImportAttribute is the attribute's actual name in the .NET Framework Class Library.

屬性參數Attribute parameters

許多屬性的參數可以是位置、未命名或具名的參數。Many attributes have parameters, which can be positional, unnamed, or named. 任何位置的參數必須以特定順序指定,而且不能省略。Any positional parameters must be specified in a certain order and cannot be omitted. 具名的參數是選擇性的,可以依照任何順序指定。Named parameters are optional and can be specified in any order. 位置參數會先指定。Positional parameters are specified first. 例如,這三個屬性是相等的:For example, these three attributes are equivalent:

[DllImport("user32.dll", SetLastError=false, ExactSpelling=false)]
[DllImport("user32.dll", ExactSpelling=false, SetLastError=false)]

第一個參數 (DLL 名稱) 是位置參數,一律會先出現;其他的則為具名參數。The first parameter, the DLL name, is positional and always comes first; the others are named. 在此案例中,這兩個具名參數預設為 false,因此可以省略。In this case, both named parameters default to false, so they can be omitted. 位置參數對應至屬性建構函式的參數。Positional parameters correspond to the parameters of the attribute constructor. 對應屬性或欄位屬性的具名或選擇性參數。Named or optional parameters correspond to either properties or fields of the attribute. 請參閱個別屬性的文件,以取得預設參數值的詳細資訊。Refer to the individual attribute's documentation for information on default parameter values.

屬性目標Attribute targets

屬性的「目標」是要套用屬性的實體。The target of an attribute is the entity which the attribute applies to. 例如,屬性可套用至類別、特定的方法或整個組件。For example, an attribute may apply to a class, a particular method, or an entire assembly. 根據預設,屬性會套用至其後的元素。By default, an attribute applies to the element that follows it. 但是,舉例來說,您也可以明確地識別是否要將屬性套用到方法、它的參數或它的傳回值。But you can also explicitly identify, for example, whether an attribute is applied to a method, or to its parameter, or to its return value.

若要明確地識別屬性目標,請使用下列語法:To explicitly identify an attribute target, use the following syntax:

[target : attribute-list]

下表顯示可能的 target 值清單。The list of possible target values is shown in the following table.

目標值Target value 適用於Applies to
assembly 整個組件Entire assembly
module 目前的組件模組Current assembly module
field 類別或結構中的欄位Field in a class or a struct
event Event - 事件Event
method 方法或 getset 屬性存取子Method or get and set property accessors
param 方法參數或 set 屬性存取子參數Method parameters or set property accessor parameters
property 屬性Property
return 方法的傳回值、屬性索引子或 get 屬性存取子Return value of a method, property indexer, or get property accessor
type 結構、類別、介面、列舉或委派Struct, class, interface, enum, or delegate

您可以指定field屬性套用至支援欄位的目標值建立自動實作屬性You would specify the field target value to apply an attribute to the backing field created for an auto-implemented property.

下列範例示範如何將屬性套用到組件和模組。The following example shows how to apply attributes to assemblies and modules. 如需詳細資訊,請參閱常見屬性 (C#)For more information, see Common Attributes (C#).

using System;
using System.Reflection;
[assembly: AssemblyTitleAttribute("Production assembly 4")]
[module: CLSCompliant(true)]

下列範例示範如何在 C# 中將屬性套用至方法、方法參數和方法傳回值。The following example shows how to apply attributes to methods, method parameters, and method return values in C#.

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

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

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


不論 ValidatedContract 定義為有效的目標為何,都必須指定 return 目標,即使 ValidatedContract 已定義為只套用至傳回值也一樣。Regardless of the targets on which ValidatedContract is defined to be valid, the return target has to be specified, even if ValidatedContract were defined to apply only to return values. 換句話說,編譯器不會使用 AttributeUsage 資訊來解析模稜兩可的屬性目標。In other words, the compiler will not use AttributeUsage information to resolve ambiguous attribute targets. 如需詳細資訊,請參閱 AttributeUsage (C#)For more information, see AttributeUsage (C#).

屬性的常見用法Common uses for attributes

下列清單包含一些程式碼中常見的屬性用法:The following list includes a few of the common uses of attributes in code:

  • 在 Web 服務中使用 WebMethod 屬性標示方法,以表示此方法應該可以透過 SOAP 通訊協定來呼叫。Marking methods using the WebMethod attribute in Web services to indicate that the method should be callable over the SOAP protocol. 如需詳細資訊,請參閱 WebMethodAttributeFor more information, see WebMethodAttribute.
  • 描述在與原生程式碼交互作用時,如何封送處理方法參數。Describing how to marshal method parameters when interoperating with native code. 如需詳細資訊,請參閱 MarshalAsAttributeFor more information, see MarshalAsAttribute.
  • 描述適用於類別、方法和介面的 COM 屬性。Describing the COM properties for classes, methods, and interfaces.
  • 使用 DllImportAttribute 類別呼叫 Unmanaged 程式碼。Calling unmanaged code using the DllImportAttribute class.
  • 針對標題、版本、描述或商標等方面來描述您的組件。Describing your assembly in terms of title, version, description, or trademark.
  • 描述要將類別的哪些成員序列化以取得持續性。Describing which members of a class to serialize for persistence.
  • 描述如何基於 XML 序列化目的,在類別成員與 XML 節點之間進行對應。Describing how to map between class members and XML nodes for XML serialization.
  • 描述方法的安全性需求。Describing the security requirements for methods.
  • 指定用來強制執行安全性的特性。Specifying characteristics used to enforce security.
  • 控制由 Just-In-Time (JIT) 編譯器所進行的最佳化,讓程式碼保持易於偵錯。Controlling optimizations by the just-in-time (JIT) compiler so the code remains easy to debug.
  • 取得有關方法之呼叫端的資訊。Obtaining information about the caller to a method.

如需詳細資訊,請參閱:For more information, see:

另請參閱See also