为什么我会收到 InvalidOperationException?

发布于 2024-11-01 21:21:11 字数 443 浏览 0 评论 0原文

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

难道是因为我同时更改了列表项?
我怎样才能防止该错误发生?

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

Could it be because i change the List items simultaneously?
How can i prevent that error from occurring?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

狼性发作 2024-11-08 21:21:11

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

Invadershots.Remove(shotItem);

这在 foreach 中是不允许的,请使用 for 代替。

This is because you trying modify collection Invadershots

Invadershots.Remove(shotItem);

This is not allowed within foreach, use for instead..

淡水深流 2024-11-08 21:21:11

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

You cannot alter a collection whilst enumerating across it. Create a clone of the collection and alter that.

芸娘子的小脾气 2024-11-08 21:21:11

您不能将元素删除到列表中,您在 foreach 中读取的元素肯定会崩溃,尝试在 foreach 中创建一个副本以将其删除,或者创建一个 for 迭代和控制正确的元素数量和输出条件。

再见

You can't do that deleting an element into a List, that you'r reading in a foreach will crash, surely, try to make a copy to remove with that while you're in the foreach, or make a for iteration and control de number of elements correctly and the out condition.

See you

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文