【发布时间】:2012-10-17 00:21:23
【问题描述】:
我想将字符串转换为其他类型。 问题是我只在运行时知道类型。 我不想使用 Select 案例。 有更好的方法吗? 更多信息: 我想在运行时构建一个表单。 因此,在 xml 中,我拥有该表单的控件,其中包含我想要设置值的所有属性:
<Controls>
<Label>
<Text>Names</Text>
<AutoSize>False</AutoSize>
<Enabled>True</Enabled>
</Label>
<TextBox>
<Text>Id:</Text>
<Enabled>FALSE</Enabled>
</TextBox>
</Controls>
不,我的代码是:
For Each elem As XElement In xmlDoc.Root.Element("Controls").Elements
Dim oType As Type
oType = FindType("System.Windows.Forms." & elem.Name.ToString) 'FindType is a function to return the type
Dim cnt As New Control
cnt = Activator.CreateInstance(oType)
For Each proper As XElement In elem.Elements
Dim propName As String = proper.Name.ToString
Dim myPropInfo As PropertyInfo = cnt.GetType().GetProperty(propName)
If myPropInfo IsNot Nothing Then
Dim val As String = proper.Value
' HERE SOMETHING TO CONVERT THE STRING TO myPropInfo.PropertyType
' Setting a value to the property
cnt.GetType().GetProperty(propName).SetValue(cnt, val, Nothing)
End If
Next
Me.FlowLayoutPanel1.Controls.Add(cnt)
Next
【问题讨论】:
-
“我不想使用 Select 案例”。为什么不呢?
-
你可以使用反射来做到这一点。
-
@JohnnyMopp:OP 已经使用反射,虽然我会使用字典来映射已知控件,并且只回退到对未知类型的反射(参见上面的链接)。