“复制它”是指如何使用自定义属性。首先定义属性:
Public Class FormattedAttribute
Inherits Attribute
Private _flag As Boolean = False
Public Sub New(ByVal b As Boolean)
_flag = b
End Sub
Public ReadOnly Property IsFormatted() As Boolean
Get
Return _flag
End Get
End Property
End Class
属性(通常)只是一个小而简单的类,它继承自Attribute。这将简单地在 Enum 上存储一个 True/False 标志:
Friend Enum MyEnum
...
<Formatted(True)> FileSize
...
Enum
注意: 约定是定义在名称后附加Attribute 的类。但在使用中,可以去掉。
属性是编译到您的应用程序中的元数据。他们提供一些关于类、属性、方法等的信息。他们自己不做任何事情。目标(类、属性等)不知道附加到它的任何属性:DefaultValue 或 Range 属性本身不执行任何操作 - 它们是供其他东西读取和使用的。
接下来,您需要一种从FormattedAttribute 读取/获取该标志的方法:
Friend Shared Function GetFormatFlag(ByVal EnumConstant As [Enum]) As Boolean
Dim fi As FieldInfo = EnumConstant.GetType().GetField(EnumConstant.ToString())
Dim attr() As FormattedAttribute= _
DirectCast( _
fi.GetCustomAttributes(GetType(FormattedAttribute), False), _
FormattedAttribute())
If attr.Length > 0 Then
Return attr(0).IsFormatted
Else
Return False
End If
End Function
这个长版本允许该属性可能存在也可能不存在于您正在搜索的类型上(就像实际使用的情况一样)。在代码中,通过调用GetFormatFlag获取它:
IsFormatted = GetFormatFlag(mi)
如果你知道该属性在那里,有一个稍微简单的方法:
Friend Shared Function GetMyKey() As String
Dim myAttr As myAttribute
myAttr = CType(Attribute.GetCustomAttribute(GetType(myClass), _
GetType(myAttribute)), myAttribute)
Return myAttr.Key
End Function
可以修改短版本以通过传递类型从任何实现它的类中获取myAttribute 值/键,但这与属性一样灵活。
它们可以与程序集、类、方法和字段一起使用,以及使用System.Reflection 获取它们的方式,并且会因类型而有所不同,但基本相同。
它们不适合在类或属性中嵌入数据,因为没有一种适合它们的方法:每个属性都需要自己的类定义和读取器方法。