System.InvalidOperationException: Collection was modified; enumeration operation may not execute.

转载:System.InvalidOperationException: Collection was modified; enumeration operation may not execute._刘宁的专栏-CSDN博客

 

今天在查看系统的Log的时候发现下面的异常抛出:

System.InvalidOperationException: Collection was modified; enumeration operation may not execute.

根据CallStack跟踪到product code中有一段相关代码(因为牵涉公司机密,现提供伪代码):

//Pseudocode

List<string> items = new List<string>();
items.Add("a");
items.Add("b");
foreach (string item in items)
{
if (item == "a")
{
items.Remove(item);
}
}

 

查了下google:You cannot change a collection while you are looping through it.

于是自己修改了下code如下:

//Pseudocode

List<string> items = new List<string>();
List<string> tempItems = new List<string>();
items.Add("a");
items.Add("b");
foreach (string item in items)
{
if (item == "a")
{
tempItems.Add(item);
}
}

foreach (string tempItem in tempItems)
{
items.Remove(tempItem);
}

 

再次编译执行,异常消失。
————————————————
版权声明:本文为CSDN博主「liuning0820」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/liuning0820/article/details/4162576

上一篇:acquaint


下一篇:5739 周赛 最高频元素的频数 滑动窗口双指针