
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 });} 总结 以上是内存溢出为你收集整理的c# – 当T未知时,如何使用反射来执行List.Cast全部内容,希望文章能够帮你解决c# – 当T未知时,如何使用反射来执行List.Cast所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)