在运行时转换类型化数组



我想基于'convertToType'或'myElementType'中声明的类型创建一个Collection。它必须是一个类型化的集合(我需要它来进一步使用)。我不想要未键入的集合。

到目前为止,我尝试的是

Dim field As PropertyInfo
'_attribute is the name of the property
field = doc.GetType().GetProperty(_attribute)
Dim convertToType As Type = field.PropertyType
Dim myElementType As Type = convertToType.GetElementType()

我试过:

Dim myList as List(Of convertToType)
Dim myList as List(Of convertToType.GetType())

数组的不同尝试。但它不起作用。我在这里做错了什么?

显然,需要一些额外的信息。我的坏:)这个方法看起来是这样的(我把它做得更小并简化了):

_attribute:属性的名称Me.Value:是从超类继承的属性(指用户选择的值)是Array[Object]

Public Overridable Overloads Sub GetData(ByRef doc As ClassA)
    Dim fieldOperator As PropertyInfo
    Dim value() As String
    fieldOperator = doc.GetType().GetProperty("operator_" & _attribute)
    fieldOperator.SetValue(doc, Me.[Operator], Nothing)
    If Me.[Operator] <> Proxy.EasyExploreServices.SearchOperator.NoSearch Then
        Dim field As PropertyInfo
        field = doc.GetType().GetProperty(_attribute)
        Dim convertToType As Type = field.PropertyType
        Dim myElementType As Type = convertToType.GetElementType()
        // DO SOME CONVERSION
        Dim arrListObject As ArrayList = New ArrayList()
        For Each myObj As Object In Me.Value
            If (myElementType Is Nothing) Then
                arrListObject.Add(Convert.ChangeType(myObj, convertToType))
            Else
                arrListObject.Add(Convert.ChangeType(myObj, myElementType))
            End If
        Next
        // END CONVERSION
        field.SetValue(doc, // My New Collection //, Nothing)
    End If
End Sub

代码中的进一步问题(如果没有进行掩盖)。字符串以外的类型抛出异常,因为例如Object[]无法转换为Int[](例如)

首先,您需要获取通用List(Of T)类的Type对象。你可以这样做:

Dim genericType As Type = GetType(List(Of ))

请注意,省略了类型参数。接下来,您需要获得List(Of T)Type对象,其中TconvertToType所描述的任何类型。要做到这一点,您可以使用MakeGenericType方法,如下所示:

Dim specificType As Type = genericType.MakeGenericType({GetType(convertToType)})

既然有了Type对象,就可以创建它的一个实例

Dim myInstance As Object = Activator.CreateInstance(specificType)

很难说在哪里做这种事情会很有用。通常,使用泛型列表的价值是在编译时获得添加的类型检查的安全性。当你通过反射创建它,然后以后期绑定的方式使用它As Object时,你似乎正在失去它的大部分价值。

最新更新