1

我想将字符串转换为其他类型。问题是我只在运行时知道类型。我不想使用 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
4

1 回答 1

2

您正在寻找的是该Convert.ChangeType方法,它接收两个参数,您要转换的字符串,以及Type您要转换为:

Dim val As Object = proper.Value
Dim targetProperty as PropertyInfo = cnt.GetType().GetProperty(propName)
Dim convertedVal = Convert.ChangeType(val, targetProperty.PropertyType)
targetProperty.SetValue(cnt, convertedVal, Nothing)
于 2012-10-16T15:36:08.020 回答