可以通过定义特性类(直接或间接 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 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
注释
如果属性类包含属性,该属性必须可读写。