c# - 无法将 List<int[*]> 转换为用反射实例化的 List<int[]>

标签 c# list generics reflection

我正在实例化一个 List<T>单维 Int32通过反射数组。当我使用以下方法实例化列表时:

Type typeInt = typeof(System.Int32);
Type typeIntArray = typeInt.MakeArrayType(1);
Type typeListGeneric = typeof(System.Collections.Generic.List<>);
Type typeList = typeListGeneric.MakeGenericType(new Type[] { typeIntArray, });

object instance = typeList.GetConstructor(Type.EmptyTypes).Invoke(null);

我在列表本身看到了这种奇怪的行为:

Watch of the list instance as an object

如果我通过反射与它交互,它似乎表现正常,但是如果我尝试将它转换为它的实际类型:

List<int[]> list = (List<int[]>)instance;

我得到这个异常:

Unable to cast object of type 'System.Collections.Generic.List`1[System.Int32[*]]' to type 'System.Collections.Generic.List`1[System.Int32[]]'.

任何想法可能导致此问题或如何解决它?我在 .net 4.0 上的 Visual Studio 2010 Express 中工作。

最佳答案

问题是由 MakeArrayType 函数引起的。您使用它的方式创建了一个一维的多维数组,这与一维数组(向量)不同。

来自documentation :

The common language runtime makes a distinction between vectors (that is, one-dimensional arrays that are always zero-based) and multidimensional arrays. A vector, which always has only one dimension, is not the same as a multidimensional array that happens to have only one dimension. You cannot use this method overload to create a vector type; if rank is 1, this method overload returns a multidimensional array type that happens to have one dimension. Use the MakeArrayType() method overload to create vector types.

改变:

Type typeIntArray = typeInt.MakeArrayType(1);

为此:

Type typeIntArray = typeInt.MakeArrayType();

创建一个普通的一维向量。

关于c# - 无法将 List<int[*]> 转换为用反射实例化的 List<int[]>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19213801/

相关文章:

c# - 如何防止 TextBox 中的退格键击键?

c# - 在类的每个属性上调用方法的表达式

android - 是否可以将 Arraylist 作为值发送到 android 中 BasicValuePair 中的单个键

c - 指针、列表和空值

java - 泛型类中出现意外的类型编译错误,可能的参数是什么?

c# - 如何获得扩展方法来更改原始对象?

c# - 流利的断言 "Maximum recursion depth was reached…"

c# - 通过 WCF 清理传入的 XML

sharepoint 验证自定义字段

c# - 向 IEnumerable 等接口(interface)添加通用扩展方法