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変換元の文字列と変換先の文字列の 2 つのパラメーターを受け取るメソッドです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 に答える