C#/.NET 4.0 中的一项新功能是您可以在 foreach
中更改您的可枚举对象而不会出现异常。请参阅 Paul Jackson 的博客条目 An Interesting Side-Effect of Concurrency: Removing Items from a Collection While Enumerating 了解有关此更改的信息。
执行以下操作的最佳方法是什么?
foreach(var item in Enumerable)
{
foreach(var item2 in item.Enumerable)
{
item.Add(new item2)
}
}
通常我使用 IList
作为缓存/缓冲区,直到 foreach
结束,但是有更好的方法吗?
最佳答案
foreach 中使用的集合是不可变的。这在很大程度上是设计使然。
正如它在 MSDN 上所说的那样:
The foreach statement is used to iterate through the collection to get the information that you want, but can not be used to add or remove items from the source collection to avoid unpredictable side effects. If you need to add or remove items from the source collection, use a for loop.
link 中的帖子Poko 提供的表明这在新的并发集合中是允许的。
关于c# - 在 'foreach' 循环中修改列表的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/759966/