您可以藉由定義屬性類別、直接或間接衍生自 Attribute的屬性類別,以建立自己的自定義屬性,以便快速且輕鬆地識別元數據中的屬性定義。 假設您想要以撰寫型別的程式設計人員名稱標記類型。 您可以定義自訂 Author 屬性類別:
<System.AttributeUsage(System.AttributeTargets.Class Or
System.AttributeTargets.Struct)>
Public Class Author
Inherits System.Attribute
Private name As String
Public version As Double
Sub New(ByVal authorName As String)
name = authorName
version = 1.0
End Sub
End Class
類別名稱是屬性的名稱 , 。 Author 其衍生自 System.Attribute,因此它是自定義屬性類別。 建構函式的參數是自定義屬性的位置參數。 在此範例中, name 是位置參數。 任何公用讀寫欄位或屬性都是具名參數。 在此情況下, version 是唯一的具名參數。 請注意,使用 AttributeUsage 屬性讓 Author 屬性只在類別和 Structure 宣告上有效。
您可以使用這個新屬性,如下所示:
<Author("P. Ackerman", Version:=1.1)>
Class SampleClass
' P. Ackerman's code goes here...
End Class
AttributeUsage 具有具名參數 , AllowMultiple您可以使用它進行自訂屬性單一使用或多重使用。 在下列程式代碼範例中,會建立 multiuse 屬性。
' multiuse attribute
<System.AttributeUsage(System.AttributeTargets.Class Or
System.AttributeTargets.Struct,
AllowMultiple:=True)>
Public Class Author
Inherits System.Attribute
在下列程式代碼範例中,相同類型的多個屬性會套用至 類別。
<Author("P. Ackerman", Version:=1.1),
Author("R. Koch", Version:=1.2)>
Class SampleClass
' P. Ackerman's code goes here...
' R. Koch's code goes here...
End Class
備註
如果您的屬性類別包含一個屬性,則該屬性必須是可讀寫的。