我一直在尝试这么做几个小时,这是我所知道的
var castItems = typeof(Enumerable).getmethod("Cast") .MakeGenericmethod(new Type[] { targettype }) .Invoke(null,new object[] { items });
这会让我回来
System.Linq.Enumerable+d__aa`1[MyObjectType]
而我需要(对于我的ViewData)作为通用列表,即
System.Collections.Generic.List`1[MyObjectType]
任何指针都会很棒
解决方法
你只需要调用ToList():
static readonly MethodInfo CastMethod = typeof(Enumerable).getmethod("Cast"); static readonly MethodInfo ToListMethod = typeof(Enumerable).getmethod("ToList"); ... var castItems = CastMethod.MakeGenericmethod(new Type[] { targettype }) .Invoke(null,new object[] { items }); var list = ToListMethod.MakeGenericmethod(new Type[] { targettype }) .Invoke(null,new object[] { castItems });
另一个选择是在你自己的类中编写一个泛型方法来做这个,并用反射来调用它:
private static List<T> CastAndList(IEnumerable items) { return items.Cast<T>().ToList(); } private static readonly MethodInfo CastAndListMethod = typeof(YourType).getmethod("CastAndList",BindingFlags.Static | BindingFlags.NonPublic); public static object CastAndList(object items,Type targettype) { return CastAndListMethod.MakeGenericmethod(new[] { targettype }) .Invoke(null,new[] { items }); }