我正在尝试遍历一堆项目,每个项目都有一个 List<> 对象数组,我想将其转换为数组数组。这是执行此操作的代码:
foreach (IngredientNode i in _snapshot._ingredientMap.Values)
{
for (int c = 0; c < NUM_TAGS; c++)
{
if (i.RecipesByTag[c] == null) continue;
i.RecipesByTag[c] = i.RecipesByTag[c].ToArray<RecipeNode>();
} <--- EXCEPTION
}
RecipesByTag 的静态类型为 IEnumerable<RecipeNode>[]
.但是,它的动态类型是 List<RecipeNode>[]
.我想遍历其中的每一个并转换 RecopeNode[] 的动态类型。在调试器下,这有效并且 i.RecipesByTag 被转换。但是,最后一个大括号会抛出异常:
尝试访问与数组不兼容的类型的元素。
我感觉发生了某种堆栈损坏。有人可以在这里解释技术层面发生的事情吗?谢谢!
迈克
最佳答案
您不必为 ToArray
指定类型参数方法,如果您使用的是强类型集合,则应该从它的用法中推断出来。这是一个泛型类型转换问题。您正试图将元素放入某种不兼容类型的数组中。
你的问题应该归结为这个(这些数组是协变的):
object[] obj = new string[1];
obj[0] = 5; // compiles fine, yields runtime error
现在,同样的东西,不同的类型(这些数组也是协变的):
IEnumerable<int>[] x = new List<int>[1];
x[0] = new int[1]; // compiles fine, yields runtime error
类型系统不喜欢这样的原因应该很明显。基本上,您将其视为 IEnumerable<int>
的数组。但它实际上是一个 List<int>
的数组.您不能将不相关的 int 类型数组放入该数组。
我相信 Eric Lippert 在他的 blog 中对此进行了很好的解释.
关于c# - 将 List<> 转换为 Array - 我得到 "Attempted to access an element as a type incompatible with the array.",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3412909/