你提出的方案實際上不會反正工作 - 它只會創建另一個List<Object>
,因爲ChangeType
返回類型爲Object
。
假設你只是想鑄造,你可以做這樣的事情:
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);
}
}
}
舊類型和新類型之間的關係是什麼?一個如何轉換到另一個? – LukeH 2010-09-29 16:25:29