決定如何使用自定義屬性類別。
AttributeUsage 是屬性,可以套用至自定義屬性定義,以控制新屬性的套用方式。 明確套用時,預設設定看起來會像這樣:
<System.AttributeUsage(System.AttributeTargets.All,
AllowMultiple:=False,
Inherited:=True)>
Class NewAttribute
Inherits System.Attribute
End Class
在此範例中,類別 NewAttribute 可以套用至任何可屬性的程式代碼實體,但只能套用至每個實體一次。 當套用至基類時,衍生類別會繼承它。
AllowMultiple和 Inherited 自變數是選擇性的,因此此程式代碼的效果相同:
<System.AttributeUsage(System.AttributeTargets.All)>
Class NewAttribute
Inherits System.Attribute
End Class
第一個 AttributeUsage 引數必須是 AttributeTargets 列舉的一或多個元素。 多個目標類型可以與 OR 運算符連結在一起,如下所示:
<AttributeUsage(AttributeTargets.Property Or AttributeTargets.Field)>
Class NewPropertyOrFieldAttribute
Inherits Attribute
End Class
如果自 AllowMultiple 變數設定為 true,則產生的屬性可以多次套用至單一實體,如下所示:
<AttributeUsage(AttributeTargets.Class, AllowMultiple:=True)>
Class MultiUseAttr
Inherits Attribute
End Class
<MultiUseAttr(), MultiUseAttr()>
Class Class1
End Class
在這裡情況下 MultiUseAttr 可以重複套用,因為 AllowMultiple 設定為 true。 套用多個屬性所顯示的兩種格式都有效。
如果 Inherited 設定為 false,則 屬性不會由衍生自屬性類別的類別繼承。 例如:
<AttributeUsage(AttributeTargets.Class, Inherited:=False)>
Class Attr1
Inherits Attribute
End Class
<Attr1()>
Class BClass
End Class
Class DClass
Inherits BClass
End Class
在這裡情況下 Attr1 ,不會透過繼承套用至 DClass 。
備註
屬性 AttributeUsage 是單一使用屬性--它不能多次套用至相同的類別。
AttributeUsage 是 AttributeUsageAttribute 的別名。
如需詳細資訊,請參閱 使用反射存取屬性(Visual Basic)。
範例
下列範例示範 Inherited 和 AllowMultiple 兩個參數對 AttributeUsage 屬性的效果,以及如何列舉套用至類別的自定義屬性。
' Create some custom attributes:
<AttributeUsage(System.AttributeTargets.Class, Inherited:=False)>
Class A1
Inherits System.Attribute
End Class
<AttributeUsage(System.AttributeTargets.Class)>
Class A2
Inherits System.Attribute
End Class
<AttributeUsage(System.AttributeTargets.Class, AllowMultiple:=True)>
Class A3
Inherits System.Attribute
End Class
' Apply custom attributes to classes:
<A1(), A2()>
Class BaseClass
End Class
<A3(), A3()>
Class DerivedClass
Inherits BaseClass
End Class
Public Class TestAttributeUsage
Sub Main()
Dim b As New BaseClass
Dim d As New DerivedClass
' Display custom attributes for each class.
Console.WriteLine("Attributes on Base Class:")
Dim attrs() As Object = b.GetType().GetCustomAttributes(True)
For Each attr In attrs
Console.WriteLine(attr)
Next
Console.WriteLine("Attributes on Derived Class:")
attrs = d.GetType().GetCustomAttributes(True)
For Each attr In attrs
Console.WriteLine(attr)
Next
End Sub
End Class
範例輸出
Attributes on Base Class:
A1
A2
Attributes on Derived Class:
A3
A3
A2