C# 如何动态调用Cast<;T>;

C# 如何动态调用Cast<;T>;,c#,generics,reflection,casting,C#,Generics,Reflection,Casting,我有一个列表,我想将其强制转换为强类型数组。问题是我在编译时不知道列表类型,因为它可能是许多对象中的一个 基本上,如果我有Type objectType=list[0].GetType()我希望能够调用list.Cast().ToArray() 我该怎么做?我尝试使用反射,如下所示: Type listType = list[0].GetType(); MethodInfo castMethod = typeof(Enumerable).GetMethod("Cast", BindingFlag

我有一个
列表
,我想将其强制转换为强类型数组。问题是我在编译时不知道列表类型,因为它可能是许多对象中的一个

基本上,如果我有
Type objectType=list[0].GetType()
我希望能够调用
list.Cast().ToArray()

我该怎么做?我尝试使用反射,如下所示:

Type listType = list[0].GetType();
MethodInfo castMethod = typeof(Enumerable).GetMethod("Cast", BindingFlags.Static | BindingFlags.Public);
castMethod = castMethod.MakeGenericMethod(new Type[] { listType });
castMethod.Invoke(null, new object[] { list});
调用返回一个CastIterator,它似乎没有公共方法。

您可以使用:

MethodInfo castMethod = typeof(Enumerable).GetMethod("Cast", BindingFlags.Static | BindingFlags.Public);
castMethod = castMethod.MakeGenericMethod(new Type[] { listType });
object castIterator = castMethod.Invoke(null, new object[] { list});
var toArrayMethod = typeof(Enumerable).GetMethod("ToArray", BindingFlags.Static | BindingFlags.Public);
toArrayMethod = toArrayMethod.MakeGenericMethod(new Type[] { listType });
object theArray = toArrayMethod.Invoke(null, new[] {castIterator});
最后,
数组将是一个强类型数组。

您可以使用:

MethodInfo castMethod = typeof(Enumerable).GetMethod("Cast", BindingFlags.Static | BindingFlags.Public);
castMethod = castMethod.MakeGenericMethod(new Type[] { listType });
object castIterator = castMethod.Invoke(null, new object[] { list});
var toArrayMethod = typeof(Enumerable).GetMethod("ToArray", BindingFlags.Static | BindingFlags.Public);
toArrayMethod = toArrayMethod.MakeGenericMethod(new Type[] { listType });
object theArray = toArrayMethod.Invoke(null, new[] {castIterator});

最后,
数组
将是一个强类型数组。

您计划如何使用结果?@ReedCopsey出现这种情况的根本原因是系统将内容存储到对象缓存中。我提前不知道类型的原因是,这是一种常见的缓存方法,它可以浅层克隆域对象以删除其持有的任何引用,以避免引用泄漏(即数据库连接、文件等)。您计划如何使用这些结果?@ReedCopsey产生这种情况的根本原因是系统将内容存储到对象缓存中。我提前不知道类型的原因是,这是一种常见的缓存方法,它可以通过浅层克隆域对象来删除其持有的任何引用,以避免引用泄漏(即数据库连接、文件等)。谢谢!真是个好东西,谢谢!工作是一种享受。