【问题标题】:Why am I getting an InvalidOperationException?为什么我会收到 InvalidOperationException?
【发布时间】:2011-04-15 10:29:29
【问题描述】:
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# winforms invalidoperationexception


    【解决方案1】:

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

    Invadershots.Remove(shotItem);
    

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

    【讨论】:

      【解决方案2】:

      在枚举集合时不能更改集合。创建集合的克隆并对其进行更改。

      【讨论】:

      • 哦,好吧,我明白了..该死的..我不知道帽子
      【解决方案3】:

      你不能这样做,将一个元素删除到一个列表中,你在 foreach 中阅读会崩溃,当然,尝试制作一个副本以在你在 foreach 中删除时,或者制作一个 for正确迭代和控制元素个数和输出条件。

      再见

      【讨论】:

        猜你喜欢
        • 2013-02-10
        • 2020-04-15
        • 1970-01-01
        • 2023-04-05
        • 2016-08-21
        • 2014-07-04
        • 2020-06-06
        • 2018-12-26
        相关资源
        最近更新 更多