确定如何使用自定义属性类。
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