我已经尝试了好几个小时了,这就是我所能做到的了
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 });
另一种选择是在您自己的类中编写一个通用方法来执行此操作,并通过反射调用 that:
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<object>.Cast<T>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1406345/