我想根据“convertToType”或“myElementType”中声明的类型创建一个集合。它必须是一个类型化的集合(我需要进一步使用它)。我不需要无类型集合。
到目前为止我尝试过的是
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:是从父类(super class)继承的属性(指用户选定的值)是一个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
代码中的进一步问题(如果没有进行转换)。 String 以外的类型会引发异常,因为例如 Object[] 无法转换为 Int[](例如)
最佳答案
首先,您需要获取通用 List(Of T)
类的 Type
对象。你可以这样做:
Dim genericType As Type = GetType(List(Of ))
请注意,类型参数被省略。接下来,您需要获取 List(Of T)
的 Type
对象,其中 T
是 convertToType< 描述的任何类型
。为此,您可以使用 MakeGenericType
方法,如下所示:
Dim specificType As Type = genericType.MakeGenericType({GetType(convertToType)})
现在您已经有了 Type
对象,您可以创建它的实例。例如:
Dim myInstance As Object = Activator.CreateInstance(specificType)
很难说做这种事情会有什么用处。通常,使用通用列表的值(value)在于您可以在编译时获得添加的类型检查的安全性。当您通过反射创建它,然后以后期绑定(bind)方式将其作为对象
使用时,看起来您正在失去它的大部分值(value)。
关于.net - 在运行时转换类型化数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20614122/