C# 当我调整数组大小时,为什么索引超出了数组的边界?
这是我正在做的程序的一小部分。我试图通过创建另一个数组手动调整数组大小,将第一个数组中的所有项目复制到第二个数组中,然后让第一个数组引用第二个数组C# 当我调整数组大小时,为什么索引超出了数组的边界?,c#,arrays,indexing,resize,indexoutofboundsexception,C#,Arrays,Indexing,Resize,Indexoutofboundsexception,这是我正在做的程序的一小部分。我试图通过创建另一个数组手动调整数组大小,将第一个数组中的所有项目复制到第二个数组中,然后让第一个数组引用第二个数组 RoundInfo[] rounds = new RoundInfo[10]; int numRounds = 0; RoundInfo ri; RoundInfo[] newRI; public void AddRound(int height, int speed) { if (numRounds >
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时,您首先输入if。 其中10==轮数。纵向为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++;
}
我不知道你在这方面的意图是什么
//如果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];
纽瑞可以去纽瑞,但不是老的。列表不需要这些,即使您必须使用数组,也有array.copy谢谢!我能修好它!
for (int i = 0; i < rounds.Length; i++)
newRI[i] = rounds[i];