1
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

3 回答 3

5

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

Invadershots.Remove(shotItem);

这在 foreach 中是不允许的,请改用 for ..

于 2011-04-15T10:31:06.063 回答
3

枚举时不能更改集合。创建集合的克隆并更改它。

于 2011-04-15T10:30:59.713 回答
1

您不能这样做,将一个元素删除到列表中,您在 foreach 中读取的内容会崩溃,当然,尝试在 foreach 中创建副本以删除该元素,或者进行 for 迭代和控制de 正确的元素数量和输出条件。

再见

于 2011-04-15T10:32:38.633 回答