2011-01-21 158 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

相关问题