【发布时间】:2017-06-15 03:30:37
【问题描述】:
这是我正在开发的程序的一小部分。我试图通过创建另一个数组来手动调整数组的大小,将第一个数组中的所有项目复制到第二个数组中,然后让第一个数组引用第二个。
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++;
}
}
如果新数组更长,我不明白为什么它会崩溃。
【问题讨论】:
-
newRI可以去newRI.Length但不是旧的。List<T>不需要这些,即使您“不得不”使用数组,也有Array.Copy
标签: c# arrays indexing resize indexoutofboundsexception