c# - 为什么会收到InvalidOperationException?

标签 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);
  }
}


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

最佳答案

您无法在枚举整个集合的同时更改其集合。创建集合的一个副本并对其进行更改。

关于c# - 为什么会收到InvalidOperationException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5675407/

相关文章:

c# - WPF 中的列表框分隔符和最终分隔符的省略

.NET 日期时间选择器平面样式

c# - 尝试使用 C# 执行命令行脚本时出现 System.InvalidOperation 异常

c# - System.InvalidOperationException 由于调用 Application.Exit() 时的集合修改

c# - 在 DataGridView 中显示 BindingList<(int, int, int)>

c# - 我应该更喜欢 'is' 还是 'as' 运算符?

带有加号的 c# URL 未通过自定义 HttpModule 运行

c# - 如何通过任务栏中的通知图标打开已关闭的表单?

c# - 在另一个线程上访问数据

c# - Datagridview CellValueChanged 事件抛出 InvalidOperationException