簡體   English   中英

為什么會收到InvalidOperationException?

[英]Why am I getting an 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);
  }
}

可能是因為我同時更改列表項嗎?
我如何防止該錯誤發生?

這是因為您嘗試修改集合Invadershots

Invadershots.Remove(shotItem);

這在foreach中是不允許的,請改為使用。

您無法在枚舉整個集合的同時更改其集合。 創建集合的一個副本並對其進行更改。

您不能這樣做,將一個元素刪除到List中,您在foreach中讀取該元素將崩潰,當然,嘗試在foreach中創建一個要刪除的副本,或者進行for迭代和控制正確定義元素的數量和out條件。

再見

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM