循环
时出现此错误An unhandled exception of type 'System.InvalidOperationException' occurred in mscorlib.dll
Additional information: Collection was modified; enumeration operation may not execute
答案 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
集合被修改的内容,您将收到错误。