C# - mscorlib.dll中的未处理异常

时间:2016-01-19 00:35:16

标签: c# winforms error-handling exception-handling html-agility-pack

循环

时出现此错误
An unhandled exception of type 'System.InvalidOperationException' occurred in mscorlib.dll
Additional information: Collection was modified; enumeration operation may not execute

1 个答案:

答案 0 :(得分:0)

您获得的错误是由以下情况引起的

foreach(var item in collection)
{
   collection.Add(newItem); // will set up the error
   collection.Remove(item); // will set up the error
}

上面的代码实际上编译成这样的东西:

IEnumerator iEnum = collection.GetEnumerator();

while (iEnum.GetNext())
{
  var item = iEnum.Current;

   collection.Add(newItem); // will set up the error
   collection.Remove(item); // will set up the error
} 

在尝试获取下一个项目之前(即在下一个循环开始时),您不会收到错误。如果修改任何IEnumerable集合,则需要保留循环而不调用GetNext()

返回的IEnumerator对象返回的IEnumerable成员

因此,如果您的代码中的某个位置在执行时,请说Players集合执行导致Players集合被修改的内容,您将收到错误。