![](/img/trans.png)
[英]Exception of type 'System.ArgumentOutOfRangeException' occurred in mscorlib.dll
[英]An unhandled exception of type 'System.ArgumentOutOfRangeException' occurred in mscorlib.dll
在以下代码中,出现以下错误。
mscorlib.dll中发生类型为'System.ArgumentOutOfRangeException'的未处理异常
附加信息:索引超出范围。 必须为非负数并且小于集合的大小。
这是代码:
public ProcessInformation GetMaxRunTimeForApplicationsBetween(DateTime StartingTime, DateTime EndingTime)
{
//Filter Based on Timer
List<ProcessInformation> filterList = new List<ProcessInformation>();
foreach (HarvestApp.ProcessInformation item in this.ProcessList)
{
if (item.started_at.CompareTo(StartingTime) >= 0 && item.ended_at.CompareTo(EndingTime) <= 0)
{
filterList.Add(item);
}
}
//Count Max Occurrence of Application
List<int> countApplicationList = new List<int>();
List<string> applicationNameList = new List<string>();
foreach (HarvestApp.ProcessInformation item in filterList)
{
if (applicationNameList.Contains(item.name))
{
countApplicationList[applicationNameList.IndexOf(item.name)]++;
}
else
{
applicationNameList.Add(item.name);
countApplicationList.Add(1);
}
}
//if (countApplicationList.Count == 0)
//{
// throw new InvalidOperationException("Empty list");
//}
int max = int.MinValue;
foreach (int item in countApplicationList)
{
if (item > max)
{
max = item;
}
}
//Return corresponding ProcessInformation Class of applicationNameList
return filterList[filterList.FindIndex(delegate
(ProcessInformation proc)
{
return proc.name.Equals(applicationNameList[countApplicationList.IndexOf(max)], StringComparison.Ordinal);
})];
}
我认为错误行在这里:
return filterList[filterList.FindIndex(delegate(ProcessInformation proc)
{
return proc.name.Equals(applicationNameList[countApplicationList.IndexOf(max)], StringComparison.Ordinal);
})];
因为List<T>.FindIndex
在找不到索引时可以返回-1
。
相反,您应该在使用索引之前测试索引是否小于0,这表明存在错误:
int result = filterList.FindIndex(delegate(ProcessInformation proc)
{
return proc.name.Equals(applicationNameList[countApplicationList.IndexOf(max)], StringComparison.Ordinal);
});
if(result < 0) throw new Exception("Cant't Find ProcessInformation");
return filterList[result];
这是问题所在:
if (applicationNameList.Contains(item.name))
{
**countApplicationList[applicationNameList.IndexOf(item.name)]++;**
}
应该是这样
if (applicationNameList.Contains(item.name) && countApplicationList.Count > applicationNameList.IndexOf(item.name))
{
countApplicationList[applicationNameList.IndexOf(item.name)]++;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.