本文主要是介绍InvalidOperationException: Collection was modified; enumeration operation may not execute.,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
今天写C#脚本,运行时报错,错误信息:
InvalidOperationException: Collection was modified; enumeration operation may not execute.
然后定位到出错行,发现是foreach循环出错,记得之前遇到过,foreach...in...里不能有remove的,奈何写的时候又忘记了。
错误代码:
foreach(GoodInfoVO info in mResGoodBagVO.M_goods){foreach (SwallowFuWenVO vo in mSwallowFuWenList){if (vo.fuwenId == info.id){info.chip -= vo.num;if (info.chip <= 0) mResGoodBagVO.M_goods.Remove(info);break;}}}
将foreach改成for循环替代就可以了:
for (int i = mResGoodBagVO.M_goods.Count - 1; i >= 0; --i ){GoodInfoVO info = mResGoodBagVO.M_goods[i];foreach (SwallowFuWenVO vo in mSwallowFuWenList){if (vo.fuwenId == info.id){info.chip -= vo.num;if (info.chip <= 0) mResGoodBagVO.M_goods.Remove(info);break;}}}
这篇关于InvalidOperationException: Collection was modified; enumeration operation may not execute.的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!