为什么我会收到 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);
}
}
难道是因为我同时更改了列表项?
我怎样才能防止该错误发生?
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是因为您尝试修改集合
Invadershots
这在 foreach 中是不允许的,请使用 for 代替。
This is because you trying modify collection
Invadershots
This is not allowed within foreach, use for instead..
您无法在枚举集合时更改集合。创建该集合的克隆并对其进行更改。
You cannot alter a collection whilst enumerating across it. Create a clone of the collection and alter that.
您不能将元素删除到列表中,您在 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