【问题标题】:Convert string to other types将字符串转换为其他类型
【发布时间】: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 已经使用反射,虽然我会使用字典来映射已知控件,并且只回退到对未知类型的反射(参见上面的链接)。

标签: vb.net type-conversion


【解决方案1】:

您正在寻找的是 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)

【讨论】:

  • 最后我不得不使用 Select Case,因为有些属性具有“未转换”类型,例如 BorderStyle,或 Convert.ChangeType 的颜色。
猜你喜欢
  • 1970-01-01
  • 2013-03-16
  • 2021-06-14
  • 2013-06-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-30
  • 1970-01-01
相关资源
最近更新 更多