2011-01-21 155 views
2

我試圖從字符串引用公共屬性。這怎麼能在vb.net中完成? 我有存儲在strucParam(i).TxtPropertyName中的「FirstName」的文本值。使用字符串動態引用對象屬性

這是目前我在做什麼:

Dim tmpValue As String 
Dim ucAppName As UserControl_appName = CType(Parent.FindControl(strucParam(i).ParentFindControl), UserControl_appName) 

tmpValue = ucAppName.FirstName.Text 

我怎樣才能在strucParam(我).TxtPropertyName使用該值,這樣我可以從我的代碼中刪除「.FirstName」?謝謝!

回答

1

這基本上是this question的重複,但我會爲你回答,因爲你是一個VB用戶,可能在你的搜索中沒有考慮C#。

假設您有一個存儲在名爲的變量中的任何類型的對象,並且存儲在名爲strPropertyName的變量中的屬性名稱。你做到以下幾點:

tmpValue = objObject.GetType().GetProperty(strPropertyName).GetValue(objObject, Nothing) 

最後要注意:請考慮刪除僞匈牙利命名法。使用像VB.NET這樣的靜態類型語言時,這沒有任何價值。

編輯:

的名字屬性在現實中是一個文本框。所以我不需要以某種方式在代碼中引用.Text?
tmpFirstName = ucAppName.GetType().GetProperty(strucParam(i).PropertyName).GetValue(objAppNav, Nothing)

試試這個:

Dim textBox as TextBox 
Dim tmpValue as String 

textBox = CType(ucAppName.GetType().GetProperty(strucParam(1).PropertyName).GetValue(objAppNav, Nothing), TextBox) 
tmpValue = textBox.Text 

基本上,您必須將屬性值轉換爲文本框類型,然後從中攫取Text屬性。

+0

我無法使用null。我不得不用Nothing來代替它。運行以下代碼時,出現「對象與目標類型不匹配」錯誤。 FirstName屬性實際上是一個文本框。所以我不需要以某種方式在代碼中引用.Text? tmpFirstName = ucAppName.GetType()。GetProperty(strucParam(i).PropertyName).GetValue(objAppNav,Nothing) – crjunk 2011-01-21 18:12:32

相關問題