Your proposed solution wouldn't actually work anyway - it'll just create another List<Object>
, because the return type of ChangeType
is Object
.
Assuming you just want casting, you could do something like this:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
class Test
{
private static List<T> ConvertListImpl<T>(List<object> list)
{
return list.ConvertAll(x => (T) x);
}
// Replace "Test" with the name of the type containing this method
private static MethodInfo methodDefinition = typeof(Test).GetMethod
("ConvertListImpl", BindingFlags.Static | BindingFlags.NonPublic);
public static IEnumerable ConvertList(List<object> list, Type type)
{
MethodInfo method = methodDefinition.MakeGenericMethod(type);
return (IEnumerable) method.Invoke(null, new object[] { list });
}
static void Main()
{
List<object> objects = new List<object> { "Hello", "there" };
List<string> strings = (List<string>) ConvertList(objects,
typeof(string));
foreach (string x in strings)
{
Console.WriteLine(x);
}
}
}