C#在foreach循环中修改字典等集合出错:System.InvalidOperationException: Collection was modified; enumeration operation may not execute.这是因为在foreach中不允许修改集合,可通过如下方式修改dictPublish的值,如:
Dictionary<string, string> _dict = new Dictionary<string, string>(dictPublish);
if ((_dict != null) && (_dict.Count != 0))
{
foreach (KeyValuePair<string, string> item in _dict)
{
dictPublish[item.Key] = "";
}
}
如果用直接赋值的方式,如Dictionary<string, string> _dict = dictPublish;也是不行的,会报同样的错误。理由嘛,引用类型所致。
时间: 2024-10-29 19:09:38