2012-10-16 32 views
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 
+0

「我不想使用選擇的情況下」。爲什麼不? – Msonic

+1

相似的C#:http://stackoverflow.com/q/811436/284240 –

+0

你可以使用反射來做到這一點。 –

回答

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) 
+0

非常感謝。 – Nianios

+0

最後,我不得不使用Select Case, 因爲一些屬性具有「未轉換」類型,如BorderStyle或Convert.ChangeType的Color。 – Nianios

相關問題