Reputation: 2520
I want to create a Collection based on type declared in 'convertToType' Or 'myElementType'. It has to be a typed collection (which I need for further use). I don't want an Untyped collection.
What I tried so far is
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()
I've tried:
Dim myList as List(Of convertToType)
Dim myList as List(Of convertToType.GetType())
Different attempts with Arrays. But it's not working. What am I doing wrong here?
Obviously some extra information is in order. My bad :) The method looks like this (i made it somewhat smaller and simplied):
_attribute: Name of the property Me.Value: Is a property inherited from the superclass (refers to a selected value by the user) is an 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
Problems further on in the code (if no coversion is made). Types other then Strings throw exception because for example Object[] cannot be converted to Int[] (for example)
Upvotes: 2
Views: 88
Reputation: 43743
First, you need to get the Type
object for the generic List(Of T)
class. You can do that like this:
Dim genericType As Type = GetType(List(Of ))
Notice that the type argument is omitted. Next, you need to get the Type
object for a List(Of T)
where T
is whatever type is described by convertToType
. To do that, you can use the MakeGenericType
method, like this:
Dim specificType As Type = genericType.MakeGenericType({GetType(convertToType)})
Now that you have the Type
object, you can create an instance of it. For instance:
Dim myInstance As Object = Activator.CreateInstance(specificType)
It's hard to say where doing this kind of thing would be very useful. Typically, the value of using a generic list is that you get the safety of the added type-checking at compile time. When you are creating it through reflection, and then using it As Object
in a late-bound manner, it would seem like you are losing most of it's value.
Upvotes: 2