【问题标题】:Getting 'Index was outside the bounds of the array.' while using foreach loop in C# [duplicate]获取“索引超出了数组的范围。”在C#中使用foreach循环时[重复]
【发布时间】: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());

    }

}

}

【问题讨论】:

标签: c# foreach indexoutofboundsexception


【解决方案1】:

我认为您误解了 foreach 循环的用法。改变-

foreach (int i in A)
    Console.Write(A[i].ToString());

到-

foreach (int i in A)
    Console.Write(i.ToString());

在上面的循环中iA 中的一个元素,而不是元素的索引。 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);就行了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-06-01
    • 2011-04-11
    • 2016-05-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-26
    • 2013-07-18
    相关资源
    最近更新 更多