集合被修改;枚举操作可能无法执行。为什么?

Collection was modified; enumeration operation may not execute. why?

抱歉,我搜索了这个错误,但这是不同的情况,对我没有帮助...

我想制作一个 Spaceship Invasion 游戏,我将所有子弹列表列为 PicutreBox。

List<PictureBox> all_bullets = new List<PictureBox>();

当您按下 Space 按钮(开火按钮)时,会创建一个新项目符号,并将其添加到表单控件和列表 all_bullets 中。

当按钮从 if (_bullet.Location.Y <= 0) 形式消失时,此代码(下方)中的 _bullet 应从 all_bullets 列表中删除。

private void tmr_bullets_Tick(object sender, EventArgs e)
{
        foreach (PictureBox _bullet in all_bullets)
        {
            _bullet.Location = new Point(_bullet.Location.X, _bullet.Location.Y - 20);

            if (_bullet.Location.Y <= 0)
            {  all_bullets.Remove(_bullet);  }
        }

        nr_bullets.Text = Convert.ToString(all_bullets.Count);

错误:

Collection was modified; enumeration operation may not execute.

抱歉,如果它被重新发布,但我没有找到我需要的东西。

在枚举集合时不能修改集合

all_bullets.Remove(_bullet);  

这将在您枚举时修改(从集合中删除项目)

你可以使用 hack 来做到这一点

foreach (PictureBox _bullet in all_bullets.ToList())