VB.net自定义属性的值

bor*_*nid 2 .net getcustomattributes

我是自定义属性的新手,所以我想知道是否有可能获得属性的值.我使用自定义属性的类中的属性示例是:

Private mFiller As String
<Position(378), Length(34), DataType("A"), ParticipantDependant("P/D"), RequiredProperty("Required"), Format("Blank")> _
Public Property Filler() As String
   Get
      Return mFiller
   End Get
   Set(ByVal value As String)
      mFiller = value
   End Set
End Property
Run Code Online (Sandbox Code Playgroud)

我正在尝试获取这些属性的值(即获取位置= 378,长度= 34等).我开始的循环看起来像这样:

Dim gwlImport As New ClientGWLImport
Dim properties() As PropertyInfo = gwlImport.GetType.GetProperties
Dim tmpInfo As PropertyInfo
For Each tmpInfo In properties
   Debug.Print("Attributes for : " & tmpInfo.Name)
   For Each tmpAttribute As Object In tmpInfo.GetCustomAttributes(True)
      Debug.Print(tmpAttribute.ToString)
   Next tmpAttribute
Next tmpInfo
Run Code Online (Sandbox Code Playgroud)

这让我得到了所有属性的名称,但我不确定如何获取值.有任何想法吗?

干杯,

瑞安

SLa*_*aks 5

您需要知道属性的类型.

例如:

Dim posAtt As PositionAttribute 
posAtt = CType(tmpInfo.GetCustomAttributes(GetType(PositionAttribute), True)(0), PositionAttribute)
'Use some property of posAtt
Run Code Online (Sandbox Code Playgroud)

顺便说一句,您不需要创建新的ClientGWLImport来获取其Type对象.
相反,你可以写

Dim properties() As PropertyInfo = GetType(ClientGWLImport).GetProperties()
Run Code Online (Sandbox Code Playgroud)

  • +1 ...我想知道为什么这会因为一个小的语法错误而失败. (2认同)