首页 > 编程语言 > 详细

在 foreach 中操作集合时报错:Collection was modified; enumeration operation may not execute.

时间:2020-05-04 11:47:42      阅读:54      评论:0      收藏:0      [点我收藏+]

错误信息:System.InvalidOperationException: Collection was modified; enumeration operation may not execute.

在foreach操作集合时候可能会遇到这个提示

原: 

foreach (var stockEnterItem in stockEnter.List_StockEnterItems)
{   //具体业务代码  }

如果出现如标题中的错误,则需要将 foreach 修改为 for。下面是修改为 foreach 为 for 后的逻辑。

var stockEnterItems = stockEnter.List_StockEnterItems;
var keys = new List<StockEnterItems>(stockEnterItems);
for (int i = 0; i < keys.Count; i++)
{
  var key = keys[i];

   ///具体业务代码

}

 

这样就可以顺利操作集合了。原因是引用类型内存地址指向同一内存地址导致的。

在 foreach 中操作集合时报错:Collection was modified; enumeration operation may not execute.

原文:https://www.cnblogs.com/llw1996/p/12825716.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!