我试图阅读大量的文件,并将一些信息存储在字典中。我的完整代码是:
[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.'如果我对CodeMappingX赋值进行注释,则没有错误,并且填充了fileList。我不明白前几行为什么会影响到这一行。有人能向我解释原因吗?
发布于 2018-07-11 09:03:55
好的,我在提交时找到了解决方案,它显然是Visual的一个错误,在调试模式中没有指向正确的行。我的第一句话应该是:
Dictionary<string, List<Tuple<string, ushort>>>[] CodeMapping = new Dictionary<string, List<Tuple<string, ushort>>>[257];发布于 2018-07-11 09:31:37
我认为您应该在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);https://stackoverflow.com/questions/51281318
复制相似问题