这段代码在 Vb.net 中的“调用”或“执行”是什么?
特别是<>_之间的内容。我了解该属性(property)在做什么。我只是不确定上面那行的意义。
<TheApp.DataHandler.ColumnAttributes("BillingClientName")> _
Public Property BillingClientName As String
Get
Return _BillingClientName
End Get
Set(ByVal value As String)
_BillingClientName = value
End Set
End Property
你能给我指出复制此功能的正确方向吗?
最佳答案
我所说的“复制”是指如何使用自定义属性。首先定义属性:
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
的小而简单的类。这个将简单地在枚举上存储 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 获取它们的方式,并且会因类型而略有不同,但基本相同。
它们不适合在类或属性中嵌入数据,因为没有一种方法适合它们:每个属性都需要自己的类定义和读取器方法。
关于vb.net - Vb.net 中的 <Something>_ 是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19575231/