共用方式為


Visual Basic 中的自訂屬性

更新:2007 年 11 月

自訂屬性 (Attribute) 是使用者定義的屬性,這些屬性會提供與程式項目相關的其他資訊。例如,您可能會定義一個自訂的安全性屬性,該屬性則指定呼叫端執行程序所需的使用權限。

根據 System.Attribute 類別在屬性類別中定義自訂屬性。屬性類別本身會使用一個名為 AttributeUsageAttribute 的屬性來提供屬性使用方法的相關資訊。指定 Inherited = True 表示屬性可以傳播至衍生類別。將 AllowMultiple 屬性 (Property) 設定為 True 讓您能將一個以上的屬性 (Attribute) 執行個體 (Instance) 套用至程式項目。AttributeTargets 列舉型別 (Enumeration) 讓您定義哪些程式項目可供您的屬性套用。

在下列程式碼中,AttributeUsageAttribute 屬性會指定一個屬性,該屬性可以被套用至任何項目型別、被繼承,而且只能套用一次:

<AttributeUsage(AttributeTargets.All, Inherited:=True, AllowMultiple:=False)> _
Class TestAttribute1
    Inherits Attribute
End Class

您可以使用 Or 運算子從 AttributeTargets 列舉型別來結合多個項目,如下列程式碼所示:

<AttributeUsage(AttributeTargets.Class Or AttributeTargets.Method)> _
Class TestAttribute2
    Inherits Attribute
End Class

在本節中

相關章節