为什么调整数组大小时索引超出数组范围?

Why is the index out of bounds of the array when I'm resizing the array?

这是我正在处理的程序的一小部分。我正在尝试通过创建另一个数组来手动调整数组的大小,将第一个数组中的所有项目复制到第二个数组,然后让第一个数组引用第二个数组。

RoundInfo[] rounds = new RoundInfo[10];
int numRounds = 0;
RoundInfo ri;
RoundInfo[] newRI;

public void AddRound(int height, int speed)
        {
            if (numRounds >= rounds.Length) // creates a new array of RI objects if numRounds is greater than rounds.Length
            {
                newRI = new RoundInfo[numRounds + 1];
               // Console.WriteLine("numRounds: {0}   length: {1}", numRounds, rounds.Length); // me checking if the AddRound correctly increments numRounds, it does.
                //Console.WriteLine(newRI.Length);
                for (int i = 0; i < newRI.Length; i++)
                    newRI[i] = rounds[i]; // *THE PROGRAM CRASHES HERE*
                rounds = newRI;
                ri = new RoundInfo(height, speed);
                rounds[numRounds] = ri;
                numRounds++;

            }
            if (numRounds < rounds.Length) // the program goes through this fine
            {
                ri = new RoundInfo(height, speed);
                rounds[numRounds] = ri;
                numRounds++;
            }

        }

如果新数组更长,我不明白为什么它会崩溃。

因为当 numRounds == rounds.Length 时,您首先进入。 其中 10==rounds.Length(即 10)

然后添加

        if (numRounds >= rounds.Length) // here you're having numRounds as 10
        {
            newRI = new RoundInfo[numRounds + 1]; //here you're adding + 1 will get newRI = new RoundInfo[11]
            for (int i = 0; i < newRI.Length; i++)
                newRI[i] = rounds[i]; // *THE PROGRAM CRASHES HERE*
                                      // so in here your program will crash due to indexOutOfBOunds because newRI[11] = rounds[11];
                                      //rounds[11] is not existing
            rounds = newRI;
            ri = new RoundInfo(height, speed);
            rounds[numRounds] = ri;
            numRounds++;
        }

您可以通过不在新 RI 上添加 +1 来防止这种情况

        if (numRounds >= rounds.Length)
        {
            newRI = new RoundInfo[numRounds]; //remove +1 here
            //etc codes
        }

不知道你这部分的意图是什么

// 如果 numRounds 大于 rounds.Length

,则创建一个新的 RI 对象数组

复制数组但超出先前数组长度是不可能的。看来你正在尝试做 (newArray[oldArray.Length + 1] == oldArray[oldArray.Length]) 你不能这样做,因为它真的会越界。

newArray[11] 不能有 oldArray[11] 因为它不存在

你可以尝试的是旧数组的长度,而不是新数组的长度

for (int i = 0; i < rounds.Length; i++)
            newRI[i] = rounds[i];