共用方式為


常見屬性 (C# 和 Visual Basic)

本主題說明在 C# 和 Visual Basic 程式中最常使用的屬性。

  • 全域屬性

  • Obsolete 屬性

  • Conditional 屬性

  • Visual Basic 屬性

全域屬性

大多數的屬性 (Attribute) 都會套用至特定的語言項目,例如類別或方法;然而,某些屬性是全域性的,它們會套用至整個組件 (Assembly) 或模組。 例如,AssemblyVersionAttribute 屬性可以用來將版本資訊內嵌至組件中,如下所示:

[assembly: AssemblyVersion("1.0.0.0")]
<Assembly: AssemblyVersion("1.0.0.0")>

全域屬性會出現在原始程式碼的任一個最上層 using 指示詞 (在 Visual Basic 中為 Imports) 後面,以及任何型別、模組或命名空間宣告前面。 全域屬性可以出現在多個原始程式檔 (Source File) 中,但是檔案必須在單一編譯行程中編譯。 在 Visual Basic 專案中,全域屬性通常會放在 Visual Basic 專案自動建立的 AssemblyInfo.vb 檔案中。 在 C# 專案中,這種屬性會放在 AssemblyInfo.cs 檔案中。

組件屬性是提供組件相關資訊的值。 這些屬性 (Attribute) 可分類如下:

  • 組件識別屬性 (Attribute)

  • 資訊屬性 (Attribute)

  • 組件資訊清單 (Assembly Manifest) 屬性 (Attribute)

  • 強式名稱屬性

組件識別屬性

三種屬性 (Attribute) (如果允許的話再加上強式名稱) 會判斷組件的識別:名稱、版本和文化特性 (Culture)。 這些屬性將形成組件的完整名稱,而且是在程式碼中參考組件時必須使用的屬性。 您可以使用屬性 (Attribute) 來設定組件的版本和文化特性。 但是,名稱值是由編譯器、組件資訊對話方塊中的 Visual Studio IDE 或「組件連結器」(Al.exe) 於建立組件時,根據包含組件資訊清單的檔案所設定。 AssemblyFlagsAttribute 屬性會指定組件的多個複本是否可以共存。

下表顯示識別屬性 (Attribute)。

屬性

用途

AssemblyName

完整描述組件的識別。

AssemblyVersionAttribute

指定組件的版本。

AssemblyCultureAttribute

指定組件所支援的文化特性。

AssemblyFlagsAttribute

指定組件是支援在同一部電腦上、同一處理序中還是同一應用程式定義域中並存執行。

資訊屬性

您可以使用資訊屬性來提供組件的其他公司或產品資訊。 下表顯示在 System.Reflection 命名空間中定義的資訊屬性。

屬性

用途

AssemblyProductAttribute

定義自訂屬性來指定組件資訊清單 (Assembly Manifest) 的產品名稱。

AssemblyTrademarkAttribute

定義自訂屬性來指定組件資訊清單的商標。

AssemblyInformationalVersionAttribute

定義自訂屬性來指定組件資訊清單的資訊版本。

AssemblyCompanyAttribute

定義自訂屬性來指定組件資訊清單的公司名稱。

AssemblyCopyrightAttribute

定義自訂屬性來指定組件資訊清單的著作權。

AssemblyFileVersionAttribute

針對 Win32 檔案版本資源,指示編譯器使用特定版本號碼。

CLSCompliantAttribute

指出組件是否符合 Common Language Specification (CLS) 標準。

組件資訊清單屬性

您可以使用組件資訊清單屬性,提供組件資訊清單中的資訊。 其中包括標題、描述、預設別名和組態。 下表顯示 System.Reflection 在命名空間中定義的組件資訊清單屬性。

屬性

用途

AssemblyTitleAttribute

定義自訂屬性來指定組件資訊清單的組件標題。

AssemblyDescriptionAttribute

定義自訂屬性來指定組件資訊清單的組件描述。

AssemblyConfigurationAttribute

定義自訂屬性來指定組件資訊清單的組件組態 (如正式版本或偵錯版本)。

AssemblyDefaultAliasAttribute

為組件資訊清單定義一個易記的預設別名

強式名稱屬性

在舊版 Visual Studio 中,使用強式名稱簽署組件的作業都是以這些組件層級屬性來進行:

這種簽署方式仍然受支援,但是簽署組件的慣用方式,是使用 [專案設計工具] 中的 [簽署頁]。 如需詳細資訊,請參閱專案設計工具、簽署頁以及 HOW TO:簽署組件 (Visual Studio)

Obsolete 屬性

Obsolete 屬性 (Attribute) 會標記不再建議使用的程式實體 (Entity)。 每次使用標記為過時的實體時,會視設定此屬性的方法,產生警告或是錯誤。 例如:

    <System.Obsolete("use class B")> 
    Class A
        Sub Method()
        End Sub
    End Class

    Class B
        <System.Obsolete("use NewMethod", True)> 
        Sub OldMethod()
        End Sub

        Sub NewMethod()
        End Sub
    End Class

[System.Obsolete("use class B")]
class A
{
    public void Method() { }
}
class B
{
    [System.Obsolete("use NewMethod", true)]
    public void OldMethod() { }
    public void NewMethod() { }
}

在此範例中,Obsolete 屬性會套用至 A 類別和 B.OldMethod 方法。 由於套用至 B.OldMethod 之屬性建構函式的第二個引數設定為 true,這個方法會產生編譯器錯誤,使用 A 類別則只會產生警告。 然而,呼叫 B.NewMethod 則不會產生任何警告或錯誤。

提供為屬性建構函式第一個引數的字串,將會顯示為警告或錯誤的一部分。 例如,在使用先前的定義時,下列程式碼會產生兩項警告和一項錯誤:

' Generates 2 warnings:
' Dim a As New A
' Generate no errors or warnings:

Dim b As New B
b.NewMethod()

' Generates an error, terminating compilation:
' b.OldMethod()
// Generates 2 warnings:
// A a = new A();

// Generate no errors or warnings:
B b = new B();
b.NewMethod();

// Generates an error, terminating compilation:
// b.OldMethod();

會對 A 類別產生兩項警告:一個針對類別參考的宣告,另一個則針對類別建構函式。

Obsolete 屬性不需要引數即可使用,不過建議的做法是包含該項目為何過時、以及應該改用什麼項目的解釋。

Obsolete 屬性是單一使用的屬性,而且可以套用至允許屬性的任何實體。 Obsolete 是 ObsoleteAttribute 的別名 (Alias)。

Conditional 屬性

Conditional 屬性會讓方法根據前置處理識別項來執行。 Conditional 屬性是 ConditionalAttribute 的別名,可以套用至方法或屬性類別。

在此範例中,Conditional 是套用至方法,以啟用或停用程式特定診斷資訊的顯示。


#Const TRACE_ON = True
Imports System
Imports System.Diagnostics
Module TestConditionalAttribute
    Public Class Trace
        <Conditional("TRACE_ON")> 
        Public Shared Sub Msg(ByVal msg As String)
            Console.WriteLine(msg)
        End Sub

    End Class

    Sub Main()
        Trace.Msg("Now in Main...")
        Console.WriteLine("Done.")
    End Sub
End Module
#define TRACE_ON
using System;
using System.Diagnostics;

public class Trace
{
    [Conditional("TRACE_ON")]
    public static void Msg(string msg)
    {
        Console.WriteLine(msg);
    }
}

public class ProgramClass
{
    static void Main()
    {
        Trace.Msg("Now in Main...");
        Console.WriteLine("Done.");
    }
}

如果未定義 TRACE_ON 識別項,就不會顯示任何追蹤輸出。

Conditional 屬性通常與 DEBUG 識別項搭配使用,以便為偵錯組建啟用追蹤和記錄功能,而不是在發行的組建中使用,如下所示:

<Conditional("DEBUG")> 
Shared Sub DebugMethod()

End Sub
[Conditional("DEBUG")]
static void DebugMethod()
{
}

呼叫標記為條件的方法時,指定的前置處理符號是否存在,將會決定是要包含或省略呼叫。 如果有定義符號,則會包括呼叫,否則,將省略呼叫。 相對於將方法封裝在 #if…#endif 區塊內,使用 Conditional 更簡潔、更雅緻,而且也是較不容易出錯的替代方法,如下所示:

#If DEBUG Then
    Sub ConditionalMethod()
    End Sub
#End If
#if DEBUG
    void ConditionalMethod()
    {
    }
#endif

條件式方法必須是類別或結構宣告中的方法,並且不能有傳回值。

使用多個識別項

如果方法擁有多個 Conditional 屬性,而至少定義了其中一個條件符號,則會包括對這個方法的呼叫 (換句話說,在邏輯上,符號全都是使用 OR 運算子連結在一起)。 在此範例中,A 或 B 的存在將會產生方法呼叫:

<Conditional("A"), Conditional("B")> 
Shared Sub DoIfAorB()

End Sub
[Conditional("A"), Conditional("B")]
static void DoIfAorB()
{
    // ...
}

若要達成邏輯上使用 AND 運算子連結符號的效果,您可以定義一系列的條件式方法。 例如,以下的第二個方法只會在 A 和 B 兩者都有定義時才會執行:

<Conditional("A")> 
Shared Sub DoIfA()
    DoIfAandB()
End Sub

<Conditional("B")> 
Shared Sub DoIfAandB()
    ' Code to execute when both A and B are defined...
End Sub
[Conditional("A")]
static void DoIfA()
{
    DoIfAandB();
}

[Conditional("B")]
static void DoIfAandB()
{
    // Code to execute when both A and B are defined...
}

為屬性類別使用條件

Conditional 屬性也可以套用至屬性類別定義。 在此範例中,只有在 DEBUG 有定義時,自訂屬性 Documentation 才會將資訊加入中繼資料。

<Conditional("DEBUG")> 
Public Class Documentation
    Inherits System.Attribute
    Private text As String
    Sub New(ByVal doc_text As String)
        text = doc_text
    End Sub
End Class

Class SampleClass
    ' This attribute will only be included if DEBUG is defined.
    <Documentation("This method displays an integer.")> 
    Shared Sub DoWork(ByVal i As Integer)
        System.Console.WriteLine(i)
    End Sub
End Class
[Conditional("DEBUG")]
public class Documentation : System.Attribute
{
    string text;

    public Documentation(string text)
    {
        this.text = text;
    }
}

class SampleClass
{
    // This attribute will only be included if DEBUG is defined.
    [Documentation("This method displays an integer.")]
    static void DoWork(int i)
    {
        System.Console.WriteLine(i.ToString());
    }
}

Visual Basic 屬性

下表列出專屬於 Visual Basic 的屬性。

屬性

用途

ComClassAttribute

對編譯器指示應當做 COM 物件公開的類別。

HideModuleNameAttribute

僅允許使用模組所需的限定性條件來存取模組成員。

VBFixedStringAttribute

在與輸入及輸出函式一起使用的結構中,指定固定長度字串的大小。

VBFixedArrayAttribute

在與輸入及輸出函式一起使用的結構中,指定固定陣列的大小。

COMClassAttribute

利用 COMClassAttribute 來簡化從 Visual Basic 建立 COM 元件的處理序。 COM 物件與 .NET Framework 組件 (Assembly) 相當不同,而且沒有 COMClassAttribute,您需要遵循很多步驟才能產生 Visual Basic 的 COM 物件。 對於標記為 COMClassAttribute 的類別,編譯器會自動執行這些步驟。

HideModuleNameAttribute

使用 HideModuleNameAttribute 後,僅能使用模組所需的限定性條件來存取模組成員。

VBFixedStringAttribute

使用 VBFixedStringAttribute 以強制 Visual Basic 建立固定長度字串。 依據預設,字串具有可變長度,在將字串儲存至檔案內時,這個屬性非常好用。 下列程式碼可說明此點:

Structure Worker
    ' The runtime uses VBFixedString to determine 
    ' if the field should be written out as a fixed size.
    <VBFixedString(10)> Public LastName As String
    <VBFixedString(7)> Public Title As String
    <VBFixedString(2)> Public Rank As String
End Structure

VBFixedArrayAttribute

使用 VBFixedArrayAttribute 來宣告固定大小的陣列。 與 Visual Basic 字串類似,依照預設,陣列具有可變長度。 在序列化或將資料寫入檔案中時,這個屬性就相當有用。

請參閱

參考

反映 (C# 和 Visual Basic)

使用反映存取屬性 (C# 和 Visual Basic)

System.Reflection

Attribute

概念

C# 程式設計手冊

使用屬性擴充中繼資料

其他資源

Visual Basic 程式設計手冊