HOW TO:提供關於元件的中繼資料描述
您可以透過 attributes 來提供您元件的說明中繼資料。 屬性 (Attribute) 是套用至程式碼項目的特定類別。 屬性在編譯階段會發出至中繼資料,接著 Common Language Runtime 或自訂工具及應用程式可透過 System.Reflection 命名空間取得中繼資料。
屬性附加至元件的方式是將屬性參考置於元件之前,並提供任何相關的參數或旗標。 呼叫建構函式在 Visual Basic 中必須置於角括弧 <> 內,在 C# 中則必須置於一般方括號 [] 內。
依照慣例,所有的屬性類別都是以 "Attribute" 結尾。例如,有 DescriptionAttribute、ObsoleteAttribute 和 BrowsableAttribute 類別。 但幾種鎖定 Common Language Runtime 的語言 (包括 Visual Basic 及 C#) 並不需要屬性的完整名稱。 例如,ObsoleteAttribute 在程式碼中可稱為 Obsolete。
若要將現有屬性附加至您的元件
判斷您元件所需要的屬性為何。
將屬性附加至您的元件。 請注意,您必須使用屬性的完整名稱或加入適當的 Imports (using) 陳述式。 下列範例示範如何附加 DescriptionAttribute 屬性:
Imports System.ComponentModel <Description("This is a description string")> Public Class TheClass End Class
using System.ComponentModel; [Description("This is a description string")] public class TheClass { }
自訂屬性
您也可以藉由繼承自 Attribute 建立自己的屬性,以搭配專屬的自訂工具或應用程式使用。 您可以將任何自訂屬性或應用程式需要的方法加入這個基底類別。
若要建立並套用自訂屬性
建立繼承自 Attribute 的類別。
Public Class WidgetAttribute Inherits System.Attribute End Class
public class WidgetAttribute: System.Attribute { }
判斷您屬性 (Attribute) 需要哪些屬性 (Property) 及方法並且為它們撰寫程式碼。 下列範例示範如何建立在 WidgetAttribute 類別的建構函式中設定的 WidgetType 屬性。 AttributeUsageAttribute 會設定該屬性的目標程式碼成員。
<AttributeUsage(System.AttributeTargets.Class)> Public Class _ WidgetAttribute Inherits System.Attribute Private mWidgetType as WidgetTypeEnum ' Creates a readonly property for the WidgetAttribute class. Public ReadOnly Property WidgetType as WidgetTypeEnum Get Return mWidgetType End Get End Property ' Creates a constructor that accepts a parameter and assigns the ' value of that parameter to the WidgetType property. Public Sub New(type as WidgetTypeEnum) MyBase.New() mWidgetType = type End Sub End Class
[AttributeUsage(System.AttributeTargets.Class)] public class WidgetAttribute: System.Attribute { private WidgetTypeEnum widgetType; // Creates a readonly property for the WidgetAttribute class. public WidgetTypeEnum WidgetType { get {return widgetType;} } public WidgetAttribute(WidgetTypeEnum type): base() { widgetType = type; } }
如同套用其他屬性一樣套用這個屬性,請確定您套用任何需要的參數。
<WidgetAttribute(WidgetTypeEnum.VerticalWidget)> _ Public Class WidgetFortyFive End Class
[WidgetAttribute(WidgetTypeEnum.VerticalWidget)] public class WidgetFortyFive { }