C# System.IndexOutOfRangeException - 索引超出数组范围

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10307407/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 13:16:51  来源:igfitidea点击:

System.IndexOutOfRangeException - Index was outside the bounds of the array

c#multidimensional-arrayoutofrangeexception

提问by Snuge

I am creating a program that imports a 2d object array of information from an excel sheet. It then passes this array to ProcessObjects method to be processed and printed/exported back out to an excel template.Can anyone tell me why I'm getting this error message?

我正在创建一个程序,该程序从 Excel 工作表中导入信息的二维对象数组。然后将此数组传递给 ProcessObjects 方法进行处理并打印/导出回 excel 模板。谁能告诉我为什么会收到此错误消息?

"An unhandled exception of type 'System.IndexOutOfRangeException' occurred in Project.exe

“Project.exe 中发生类型为“System.IndexOutOfRangeException”的未处理异常

Additional information: Index was outside the bounds of the array."

附加信息:索引超出数组范围。”

private void ProcessObjects(object[,] classesArray, object[,] classesAvailabilityArray, Excel.Workbook workbook2, Excel.Sheets excelSheets)
{
    // once classes are selected, they are copied to a temporary location
    // while they're waiting to be printed
    object[,] tempArray = new object[6,3];

    // This stops the while loop once enough credit hours have been taken 
    // It must reach 123 hours for CS Degree .
    int hourCounter = 0;

    int iteration = 0;

    while (hourCounter < 123)
        {
            // this while loop copies some classes from classesArray to tempArray
            // so they can be printed into the excel template (NewStudentTemplateCS.xlsx)
            //
            int classes = 0, hours = 0; // stops while loop if limit is reached
            int w = 0, x = 0; // used to select individual elements of tempArray (0 based)
                              // w = row
                              // x = column
            int y = 1, z = 1; // used to select individual elements of classesArray (1 based)
                              // y = row
                              // z = column
            while(classes < 7 || hours < 17)
            {
                // this loop checks the status of the flag and stops at the first avaliable
                // class/row of classesArray
                while (classesArray[y,7] == (object)1)
                {
                    y++;
                }

                // copies the call EX: "MATH 2313" from classesArray to tempArray
                tempArray[w,x] = classesArray[y,z];
                x += 2;
                z += 2;
                // copies the name EX: "Calculus I" from classesArray to tempArray
                tempArray[w, x] = classesArray[y, z];
                x++;
                z++;
                // Copies the hours EX: "3" from classesArray to tempArray
                tempArray[w, x] = classesArray[y, z];

                Console.WriteLine("debug test");

                // increments classes, hours, and hourCounter for exit decision
                classes += 1;
                hours += (int)classesArray[y, z];
                hourCounter += (int)classesArray[y, z];

                // sets flag to one
                z += 3;
                classesArray[y, z] = 1;

            }// end while loop

            // print method that prints temp array and clears tempArray for next use
            PrintArray(tempArray, iteration, workbook2, excelSheets);

            // iterates iteration
            iteration++;

        } // end while loop
        // print method that prints temp array and clears tempArray for next use
        PrintArray(tempArray, iteration, workbook2, excelSheets);

        // iterates iteration
        iteration++;

    } // end while loop
} // end ProcessObjects method

I have commented out each of the following lines individually, but each line of code all returns the same error I listed above.

我已经单独注释了以下每一行,但每一行代码都返回与我上面列出的相同的错误。

Console.WriteLine("debug test");

// increments classes, hours, and hourCounter for exit decision
classes += 1;
hours += (int)classesArray[y, z];
hourCounter += (int)classesArray[y, z];

// sets flag to one
z += 3;
classesArray[y, z] = 1;

回答by danielcooperxyz

The integers you are using (i.e. w,x,y,z) are becoming bigger than the defined array size. You should add breakpoints into the code so you can see what is happening during compiling and see where they are becoming bigger than expected by the array definitions.

您使用的整数(即 w、x、y、z)变得大于定义的数组大小。您应该在代码中添加断点,以便您可以查看编译期间发生的情况,并查看它们在哪里变得比数组定义预期的要大。

The rules of your loop, generally, are used to stop index out of bounds exceptions occurring. I would suggest breaking up the code a bit, there seems to be a lot of stuff going on, but it seems to be too much for this loop.

通常,循环规则用于阻止索引越界异常的发生。我建议将代码分解一下,似乎有很多东西在进行,但对于这个循环来说似乎太多了。

回答by Dour High Arch

Step through your code in the debugger:

在调试器中逐步执行您的代码:

object[,] tempArray = new object[6,3];

You are creating an array with max indexes at tempArray[5, 2]. Then you start looping. At the start of each loop:

您正在创建一个最大索引为 的数组tempArray[5, 2]。然后你开始循环。在每个循环开始时:

int w = 0, x = 0;

Then in the body of the loop:

然后在循环体中:

tempArray[w,x] = classesArray[y,z];

You assign to tempArray[0, 0]

你分配给 tempArray[0, 0]

x += 2;
z += 2;
tempArray[w, x] = classesArray[y, z];

You assign to tempArray[0, 2]

你分配给 tempArray[0, 2]

x++;
z++;
// Copies the hours EX: "3" from classesArray to tempArray
tempArray[w, x] = classesArray[y, z];

You assign to tempArray[0, 3]. But the maximum index of tempArrayis [0, 2]; your array index is out of range, exactly what the exception was telling you.

您分配给tempArray[0, 3]. 但是的最大索引tempArray是[0, 2];您的数组索引超出范围,这正是异常告诉您的。

If you can be certain that yand zcan never go outside the bounds of classesArray, you can declare tempArraylike this:

如果您可以确定y并且z永远不会超出 的范围classesArray,您可以这样声明tempArray

object[,] tempArray = new object[classesArray.GetLength(0), classesArray.GetLength(1)];

But with all those hard-coded magic numbers, and trying to synchronize arrays with differing bases, this is very risky code.

但是对于所有这些硬编码的幻数,并尝试同步具有不同基数的数组,这是非常危险的代码。