套用屬性

使用下列流程將屬性套用至程式碼的元素。

  1. 定義新的屬性或使用現有的 .NET 屬性。

  2. 將屬性放在緊接於程式碼元素前面,以套用屬性。

    每個語言有其自己的屬性語法。 在 C++ 和 C# 中,屬性以方括弧括住,而且與元素之間以空白字元隔開,其中可包含分行符號。 在 Visual Basic 中,屬性以角括弧括住,而且必須在相同的邏輯行。如果想要分行符號,可以使用行接續字元。

  3. 指定屬性的位置參數和具名參數。

    位置參數是必要的,而且必須位於任何具名參數前面。它們對應至屬性的其中一個建構函式的參數。 具名參數是選擇性,對應至屬性的讀取/寫入屬性。 在 C++ 和 C# 中,指定每一個選擇性參數的 name=value,其中 name 是屬性的名稱。 在 Visual Basic 中,指定 name:=value

當您編譯程式碼時,屬性會發出至中繼資料,並透過執行階段反映服務,提供給通用語言執行平台及任何自訂工具或應用程式使用。

依照慣例,所有屬性名稱的結尾都是 "Attribute"。 不過,有幾種以 Visual Basic 和 C# 等執行階段為目標的語言,並不需要您指定屬性的全名。 例如,如果您想要初始化 System.ObsoleteAttribute,則只需要將其參考為已淘汰

將屬性套用至方法

下列程式碼範例示範如何使用 System.ObsoleteAttribute,將程式碼標記為已淘汰。 "Will be removed in next version" 字串會傳遞至屬性。 當呼叫這個屬性所描述的程式碼時,屬性會產生編譯器警告來顯示傳遞的字串。

public ref class Example
{
    // Specify attributes between square brackets in C#.
    // This attribute is applied only to the Add method.
public:
    [Obsolete("Will be removed in next version.")]
    static int Add(int a, int b)
    {
        return (a + b);
    }
};

ref class Test
{
public:
    static void Main()
    {
        // This generates a compile-time warning.
        int i = Example::Add(2, 2);
    }
};

int main()
{
    Test::Main();
}
public class Example
{
    // Specify attributes between square brackets in C#.
    // This attribute is applied only to the Add method.
    [Obsolete("Will be removed in next version.")]
    public static int Add(int a, int b)
    {
        return (a + b);
    }
}

class Test
{
    public static void Main()
    {
        // This generates a compile-time warning.
        int i = Example.Add(2, 2);
    }
}
Public Class Example
    ' Specify attributes between square brackets in C#.
    ' This attribute is applied only to the Add method.
    <Obsolete("Will be removed in next version.")>
    Public Shared Function Add(a As Integer, b As Integer) As Integer
        Return a + b
    End Function
End Class

Class Test
    Public Shared Sub Main()
        ' This generates a compile-time warning.
        Dim i As Integer = Example.Add(2, 2)
    End Sub
End Class

在組件層級套用屬性

如果您想要在組件層級套用屬性,請使用 assembly (在 Visual Basic 中為 Assembly) 關鍵字。 下列程式碼顯示在組件層級套用的 AssemblyTitleAttribute

using namespace System::Reflection;
[assembly:AssemblyTitle("My Assembly")];
using System.Reflection;
[assembly:AssemblyTitle("My Assembly")]
Imports System.Reflection
<Assembly: AssemblyTitle("My Assembly")>

套用此屬性時,字串 "My Assembly" 會放在檔案的中繼資料部分中的組件資訊清單。 您可以使用 IL 反組譯工具 (Ildasm.exe) 或建立自訂程式擷取屬性,以檢視屬性。

另請參閱