我正在实例化一个 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);
我在列表本身看到了这种奇怪的行为:
如果我通过反射与它交互,它似乎表现正常,但是如果我尝试将它转换为它的实际类型:
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/