vendredi 20 février 2015

How to determine the type of an generic array element with reflection?

What I'm trying to do is without generic types simple.



SomeType[] s = new SomeType[5];
for(int i = 0; i < 5: i++){
s[i]= new SomeType();
}


Using generics this is what I have so far.



private static T TypeMapper<T>(dynamic handle) {

if (typeof(T).IsArray)
{
Type elementType = typeof(T).GetElementType();
int arrayLength = handle.Length;
Array array = Array.CreateInstance(elementType, arrayLength);

//??? How to get the type of an generic array element
Type typeOfthis = typeof(array[0]).GetElementType();

for (int i = 0; i < arrayLength; i++)
{
//??? How to create an instance from it.
array[i] = new typeOfthis ();
}


T obj = (T)(object)array;
return obj;
}
else
{}


Then calling the TypeMapper function with.



dynamic t = new TextSpan[4];
var result = TypeMapper<TextSpan[]>(t)


How can I get the type of an generic array element.



Type typeOfthis = typeof(array[0]).GetElementType();//Not Working


And how to create an instance from it.



array[i] = new typeOfthis ();


Your help is highly appreciated.






Aucun commentaire:

Enregistrer un commentaire