在 C# 中使用 foreach 循环时获取 'Index was outside the bounds of the array.'
Getting 'Index was outside the bounds of the array.' while using foreach loop in C#
我在尝试使用 foreach 循环打印数组值时在 运行 时收到“System.IndexOutOfRangeException: 'Index was outside the bounds of the array.'”错误。我调试了 visual studio 中的问题,可以看到我在 foreach 中一直到 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());
}
}
}
我想你误解了 foreach 循环的用法。变化-
foreach (int i in A)
Console.Write(A[i].ToString());
到-
foreach (int i in A)
Console.Write(i.ToString());
在上面的循环中 i
是 A
中的一个元素,而不是元素的索引。 For 循环将为您提供索引:
for (int i = 0; i < A.Length; i++)
Console.WriteLine(A[i].ToString());
考虑此示例以了解 for 循环和 foreach 循环的用法:
int[] test = { 9, 8, 7, 6, 5, 4 };
foreach (int i in test)
Console.WriteLine(i);
Console.WriteLine();
for (int i = 0; i < test.Length; i++)
Console.WriteLine(i);
Console.WriteLine();
for (int i = 0; i < test.Length; i++)
Console.WriteLine(A[i]);
// Output:
// 9
// 8
// 7
// 6
// 5
// 4
//
// 0
// 1
// 2
// 3
// 4
// 5
//
// 9
// 8
// 7
// 6
// 5
// 4
还要注意,当您想要打印整数时,不需要 .ToString()
。直接写 Console.WriteLine(myInteger);
.
我在尝试使用 foreach 循环打印数组值时在 运行 时收到“System.IndexOutOfRangeException: 'Index was outside the bounds of the array.'”错误。我调试了 visual studio 中的问题,可以看到我在 foreach 中一直到 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());
}
}
}
我想你误解了 foreach 循环的用法。变化-
foreach (int i in A)
Console.Write(A[i].ToString());
到-
foreach (int i in A)
Console.Write(i.ToString());
在上面的循环中 i
是 A
中的一个元素,而不是元素的索引。 For 循环将为您提供索引:
for (int i = 0; i < A.Length; i++)
Console.WriteLine(A[i].ToString());
考虑此示例以了解 for 循环和 foreach 循环的用法:
int[] test = { 9, 8, 7, 6, 5, 4 };
foreach (int i in test)
Console.WriteLine(i);
Console.WriteLine();
for (int i = 0; i < test.Length; i++)
Console.WriteLine(i);
Console.WriteLine();
for (int i = 0; i < test.Length; i++)
Console.WriteLine(A[i]);
// Output:
// 9
// 8
// 7
// 6
// 5
// 4
//
// 0
// 1
// 2
// 3
// 4
// 5
//
// 9
// 8
// 7
// 6
// 5
// 4
还要注意,当您想要打印整数时,不需要 .ToString()
。直接写 Console.WriteLine(myInteger);
.