IndexOutOfRange on GetFiles



我正在尝试读取大量文件并将一些信息存储在字典中。我的完整代码是:

[HttpGet("[action]")]
public JsonResult GenerateMapFiles()
{
Dictionary<string, List<Tuple<string, ushort>>>[] CodeMapping = new Dictionary<string, List<Tuple<string, ushort>>>[256];
/* Pre-creating some dictionaries */
CodeMapping[2] = new  Dictionary<string, List<Tuple<string, ushort>>>(256);
CodeMapping[8] = new  Dictionary<string, List<Tuple<string, ushort>>>(256);
CodeMapping[16] = new  Dictionary<string, List<Tuple<string, ushort>>>(256);
CodeMapping[32] = new  Dictionary<string, List<Tuple<string, ushort>>>(256);
CodeMapping[64] = new  Dictionary<string, List<Tuple<string, ushort>>>(256);
CodeMapping[128] = new  Dictionary<string, List<Tuple<string, ushort>>>(256);
CodeMapping[256] = new  Dictionary<string, List<Tuple<string, ushort>>>(256);
string[] fileList = System.IO.Directory.GetFiles("C:\mySQL");
/* Processing code was here, but I commented it and it is still generating exception */
return Json(CodeMapping);
}

string[] fileList = System.IO.Directory.GetFiles("C:\mySQL");行引发异常:

Exception thrown: 'System.IndexOutOfRangeException' in XXXXX.dll: 'Index was outside the bounds of the array.'

如果我对CodeMapping[X]赋值进行注释,则不会出现错误,并且会填充fileList。我不明白为什么前几行会影响这一行。有人能向我解释为什么吗?

好的,我在提交时找到了解决方案,这显然是Visual Studio在调试模式中没有指向正确的行的错误。我的第一句话应该是:

Dictionary<string, List<Tuple<string, ushort>>>[] CodeMapping = new Dictionary<string, List<Tuple<string, ushort>>>[257];

我认为您应该在n-1个位置创建字典,因为在256个元素的集合中,最大索引将从0到255。

所以你把它重写为:

/* Pre-creating some dictionaries */
CodeMapping[1] = new  Dictionary<string, List<Tuple<string, ushort>>>(256);
CodeMapping[7] = new  Dictionary<string, List<Tuple<string, ushort>>>(256);
CodeMapping[15] = new  Dictionary<string, List<Tuple<string, ushort>>>(256);
CodeMapping[31] = new  Dictionary<string, List<Tuple<string, ushort>>>(256);
CodeMapping[63] = new  Dictionary<string, List<Tuple<string, ushort>>>(256);
CodeMapping[127] = new  Dictionary<string, List<Tuple<string, ushort>>>(256);
CodeMapping[255] = new  Dictionary<string, List<Tuple<string, ushort>>>(256);

相关内容

  • 没有找到相关文章

最新更新