c# – 当T未知时,如何使用反射来执行List.Cast

我一直在尝试这么做几个小时,这是我所知道的
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 });
}

相关文章

在要实现单例模式的类当中添加如下代码:实例化的时候:frmC...
1、如果制作圆角窗体,窗体先继承DOTNETBAR的:public parti...
根据网上资料,自己很粗略的实现了一个winform搜索提示,但是...
近期在做DSOFramer这个控件,打算自己弄一个自定义控件来封装...
今天玩了一把WMI,查询了一下电脑的硬件信息,感觉很多代码都...
最近在研究WinWordControl这个控件,因为上级要求在系统里,...