[英]C# Array of List Index out of bounds
我已经制作了一个程序,可以从文件中提取一些信息,对其进行一些操作,然后将其存储回列表中。 通过此链接: c#中是否可能有二维列表? 我已经能够创建一个包含适合我需求的列表的课程。 但是经过一些调试后,我发现我在每次循环迭代时都覆盖了列表。 然后,我决定制作一个列表数组-单击此链接: 如何在C#中创建List <int>数组?
创建一个列表数组,对其进行初始化并添加元素。 但是,当它需要移动到下一个列表位置时,就会抛出边界外异常。
我已经尝试了几件事(阅读了有关比赛状况的信息),但没有一件事奏效。 仅当我用代码打开多个文件时,才会发生此问题; 否则,它会完美运行。
在当前文件的最后一次迭代中,xmldata抛出异常。 例如:选择两个文件,每个文件将添加五个元素。 在第一个文件的最后一个元素中,将引发异常,并且要在最后一个元素的位置添加数据。
附加信息:索引超出了数组的范围。 (抛出异常)。
任何帮助将不胜感激。 非常感谢。
码:
List<xmldata>[] finalcontent = new List<xmldata>[9999];
finalcontent[listpos] = new List<xmldata>();//Initializing a list for each filename
foreach (Match m in matches)
{
Double[] numbers;
string aux;
aux = m.Groups[1].ToString();
aux = Regex.Replace(aux, @"\s+", "|");
string[] numbers_str = aux.Split(new[] { "|" }, StringSplitOptions.RemoveEmptyEntries);
numbers = new Double[numbers_str.Length];
for (int j = 0; j < numbers.Length; j++)
{
numbers[j] = Double.Parse(numbers_str[j], CultureInfo.InvariantCulture);
//Converts each number on the string to a Double number, store it in a position
//in the Double array
numbers[j] = numbers[j] / 100; //Needed calculus
numbers[j] = Math.Round(numbers[j], 3); //Storing numbers rounded
}
string values = String.Join(" ", numbers.Select(f => f.ToString()));
if (i <= colors_str.Length)
{
finalcontent[listpos].Add(new xmldata//The exception is thrown right here
{
colorname = colors_str[i],
colorvalues = values,
});//Closing list add declaration
}//Closing if
i++;
}//Closing foreach loop
链接到文件: https : //drive.google.com/file/d/0BwU9_GrFRYrTT0ZTS2dRMUhIWms/view?usp=sharing
数组是固定大小的,但是列表会随着新项目的添加自动调整大小。
因此,相反,既然您仍在使用列表,为什么不使用列表列表呢?
List<List<int>> ListOfListsOfInt = new List<List<int>>();
然后,如果您确实绝对必须有一个数组,那么可以得到一个这样的数组:
ListOfListsOfString.ToArray();
// Convert non-ascii characters to .
for (int jx = 0; jx < cnt; ++jx)
if (line[jx] < 0x20 || line[jx] > 0x7f) line[jx] = (byte)'.';
这是一个很大的例子,但是请检查一下这个例子。 您在输入语句之前增加了“ jx”,可能超出了cnt的范围?
使用列表时-最好使用本机函数。
List<xmldata>[] finalcontent = new List<xmldata>();
......
finalcontent[listpos] = new List<xmldata>(); insted of var _tmpVariable = new List<xmldata>();//Initializing a list for each filename
......
_tmpVariable.Add(new xmldata
{
colorname = colors_str[i],
colorvalues = values,
});//Closing list add declaration
fs.Close();//closing current file
listpos++;//Increment list position counter
finalcontent.Add(_tmpVariable); // add list into list
由于没有异常详细信息,因此很难找到引发异常的位置。 它可能是列表问题,字符串问题或其他(甚至是文件读取问题),因此请使用当前的异常详细信息进行更新。
尝试更改以下内容:
if (i <= colors_str.Length)
至
if (i < colors_str.Length).
实际上,我确信这是问题所在。
这是因为引用从0开始,最后一个引用是长度-1,而不是长度。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.