2009-12-21 92 views
2

我新的自定義屬性,所以我不知道是否有可能獲得屬性的值。在我的課,我使用自定義屬性,屬性的一個例子是:VB.net屬性值

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 

我試圖讓這些屬性的值(即獲取位置= 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 

這讓我的所有屬性的名字,但我不知道如何得到的值。有任何想法嗎?

乾杯,

瑞安

回答

4

您需要知道屬性的類型。

例如:

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

順便說一句,你並不需要創建一個新的ClientGWLImport,以獲取其Type對象。
相反,你可以寫

Dim properties() As PropertyInfo = GetType(ClientGWLImport).GetProperties() 
+0

posAtt = tmpInfo.GetCustomAttributes(的GetType(PositionAttribute),真)(0)作爲PositionAttribute ????新的語法? – Codezy 2009-12-21 18:25:28

+0

除了語法錯誤之外,它正是我正在尋找的。它應該閱讀: posAtt = CTYPE(tmpInfo.GetCustomAttributes(的GetType(PositionAttribute),真)(0),PositionAttribute) – bornbnid 2009-12-21 18:28:03

+0

很抱歉的語法錯誤;我太習慣C#了。 – SLaks 2009-12-21 19:24:56

0

System.Reflection.CustomAttributeData類公開的功能,用於檢索裝飾類型或成員自定義屬性的完整定義。

+0

這應該僅用於在僅反射上下文中加載的代碼。對於普通的代碼,你應該使用'GetCustomAttributes',這可能會更快,當然更簡單。看到我的答案。 – SLaks 2009-12-21 17:07:35

+0

@SLaks:儘管CustomAttributeData類最初可能被設計爲支持某些本來無法在僅反射的上下文中工作的事實,但它對於通常加載的程序集來說工作得很好。這在文檔中明確說明:「CustomAttributeData可用於執行上下文以及僅反射上下文中。」 如果屬性的類型是衆所周知的,你的做法顯然是可取的。但是,我閱讀原始文章是爲了請求通用方法來讀取完整的屬性數據。 – 2009-12-21 18:29:45