使用字符串动态引用对象属性

时间:2011-01-21 17:14:24

标签: asp.net vb.net

我正在尝试从字符串引用公共属性。怎么能在vb.net中完成? 我将文本值“FirstName”存储在strucParam(i).TxtPropertyName中。

这就是我目前正在做的事情:

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

tmpValue = ucAppName.FirstName.Text

如何使用strucParam(i).TxtPropertyName中的值,以便从代码中删除“.FirstName”?谢谢!

1 个答案:

答案 0 :(得分:1)

这基本上是this question的副本,但我会为你回答,因为你是VB用户,可能在你的搜索中没有考虑C#。

假设您有一个存储在名为objObject的变量中的任何类型的对象,以及存储在名为strPropertyName的变量中的属性的名称。您执行以下操作:

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

最后请注意:请考虑删除伪匈牙利语符号。使用像VB.NET这样的静态类型语言时,这没什么价值。

修改:

  

FirstName属性实际上是一个文本框。所以我不需要以某种方式引用。代码中的.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

基本上,您必须将属性的值强制转换为TextBox类型,然后从中获取Text属性。