C#防止收集已修改的异常 [英] C# preventing Collection Was Modified exception

查看:86
本文介绍了C#防止收集已修改的异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 foreach(T value in new List<T>(oldList) )

是危险的

更广泛地说,枚举在oldList中的最佳方式是给定元素可以在枚举期间添加/删除...

More generaly what is the best way to enumerate over oldList given that elements can be added/removed during the enumeration...

推荐答案

一般的规则是,你不应该修改你枚举的同一个集合。如果你想这样做,保持另一个集合,将跟踪哪些元素添加/从原始集合中删除,然后退出循环,对原始集合执行添加/删除操作。

The general rule is, you should not modify the same collection in which you are enumerating. If you want to do something like that, keep another collection which will keep track of which elements to add/remove from the original collection and then after exiting from the loop, perform the add/remove operation on the original collection.

这篇关于C#防止收集已修改的异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆