【发布时间】:2020-11-01 06:51:34
【问题描述】:
在尝试使用 foreach 循环打印数组值时,我在运行时收到“System.IndexOutOfRangeException: 'Index was outside the bounds of the array.'”错误。我在 Visual Studio 中调试了这个问题,可以看到 foreach 中的 i 将持续到 7 超出范围。 foreach 循环自动获取数组的所有元素,所以请帮助我理解错误的原因? 下面是函数:
void Sort(int[] A)
{
for (int i = 1; i < A.Length; i++)
{
int key = A[i];
int j = i - 1;
while (j >= 0 && A[j] > key)
{
A[j + 1] = A[j];
j = j - 1;
}
A[j + 1] = key;
}
foreach (int i in A)
Console.Write(A[i].ToString());
}
}
}
【问题讨论】:
-
哪一行有异常?
-
最后一行:Console.Write(A[b].ToString());
-
好吧,如果
A包含,比如说,-12345项目,你会遇到错误:A没有-12345th 项目 -
它正在使用 Console.Write(i);,谢谢!我明白我的错误。 'i' 表示数组的元素,而不是 foreach 循环中的索引。
标签: c# foreach indexoutofboundsexception