为什么我会收到InvalidOperationException?

时间:2011-04-15 10:29:30

标签: c# winforms invalidoperationexception

foreach (var shotItem in Invadershots)// it points to me to there and doesnt allow me to loop.."{"Collection was modified; enumeration operation may not execute."}"
{
  shotItem.Move();// it happens when this simple method called (which actually checks some bool..if the shot was out of the winform).
  if (shotItem.removeShot)
  {
        Invadershots.Remove(shotItem);
  }
}

可能是因为我同时更改了列表项目了吗? 如何防止发生错误?

4 个答案:

答案 0 :(得分:5)

这是因为您尝试修改集合Invadershots

Invadershots.Remove(shotItem);

在foreach中不允许这样做,而是用于..

答案 1 :(得分:3)

在对其进行枚举时,您无法更改集合。创建集合的克隆并更改它。

答案 2 :(得分:1)

你无法将一个元素删除到一个列表中,你在foreach中阅读会崩溃,当然,当你在foreach中时,尝试制作一个副本以删除它,或者为了迭代和控制正确的元素数量和out条件。

见到你

答案 3 :(得分:0)

您需要以与我的回答here类似的方式遍历该集合。

相关问题