Ant*_*ain 10 c# generics reflection casting
我一直试着这么做几个小时,这就是我所拥有的
var castItems = typeof(Enumerable).GetMethod("Cast")
.MakeGenericMethod(new Type[] { targetType })
.Invoke(null, new object[] { items });
Run Code Online (Sandbox Code Playgroud)
这让我回头
System.Linq.Enumerable + d__aa`1 [MyObjectType]
而我需要(对于我的ViewData)作为通用列表即
System.Collections.Generic.List`1 [MyObjectType]
任何指针都会很棒
Jon*_*eet 17
你只需要在它之后调用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 });
Run Code Online (Sandbox Code Playgroud)
另一种选择是在你自己的类中编写一个通用方法来执行此操作,并使用反射调用它:
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 });
}
Run Code Online (Sandbox Code Playgroud)