简体   繁体   English

修改错误的集合

[英]Error modified collection

I always get the collection was modified error when adding elements to List<> while it is being used in for i or foreach loops and it makes cross threading a little bit complicated. 当在i或foreach循环中使用List <>时,将元素添加到List <>时,我总是会收到该集合被修改的错误,这会使交叉线程有点复杂。 Is there a special class I'm missing that will not make the enumerator invalid if the collection is modified? 我是否缺少特殊类,如果修改了集合,该类不会使枚举器无效?

If you are trying to add or remove items from the collection you are looping from then you will receive a InvalidOperationException . 如果尝试从循环中添加或删除集合中的项目,则将收到InvalidOperationException

To avoid that you need to either create and iterate over a copy of the array/list you are currently iterating from or create a temporary list to host the changes you are making then use that one to update your original source. 为了避免这种情况,您需要创建并迭代当前要从其访问的阵列/列表的副本,或者创建一个临时列表来承载您所做的更改,然后使用该列表来更新原始源。

就从集合中删除(删除)项目而言,您还可以向后遍历集合的副本并根据需要删除项目,这不会造成麻烦,因为这不会对剩余项目的索引产生负面影响被迭代。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM