c# - 是否有修改不会使迭代器失效的 C# 集合?

标签 c# .net collections iterator

在 C# Collections 库中是否存在修改结构不会使迭代器失效的数据结构?

考虑以下几点:

List<int> myList = new List<int>();
myList.Add( 1 );
myList.Add( 2 );
List<int>.Enumerator myIter = myList.GetEnumerator();
myIter.MoveNext();  // myIter.Current == 1
myList.Add( 3 );
myIter.MoveNext();  // throws InvalidOperationException

最佳答案

是的,看看 System.Collections.Concurrent .NET 4.0 中的命名空间。

请注意,对于此命名空间中的某些集合(例如 ConcurrentQueue<T>),这仅通过在相关集合的“快照”上公开枚举器来工作。

来自 the MSDN documentation on ConcurrentQueue<T> :

The enumeration represents a moment-in-time snapshot of the contents of the queue. It does not reflect any updates to the collection after GetEnumerator was called. The enumerator is safe to use concurrently with reads from and writes to the queue.

不过,并非所有系列都如此。 ConcurrentDictionary<TKey, TValue> ,例如,为您提供一个枚举器,该枚举器在调用 MoveNext 之间维护对基础集合的更新。 .

来自 the MSDN documentation on ConcurrentDictionary<TKey, TValue> :

The enumerator returned from the dictionary is safe to use concurrently with reads and writes to the dictionary, however it does not represent a moment-in-time snapshot of the dictionary. The contents exposed through the enumerator may contain modifications made to the dictionary after GetEnumerator was called.

如果您没有 4.0,那么我认为其他人是对的,.NET 没有提供这样的集合。但是,您始终可以通过做同样的事情来构建自己的 ConcurrentQueue<T>确实(遍历快照)。

关于c# - 是否有修改不会使迭代器失效的 C# 集合?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2753724/

相关文章:

c# - Oracle 更改通知包含无效操作

C# 如何在多个列表框中显示项目?

c# - 如何激活由另一个进程启动的窗口

c# - 从网络摄像头获取输入

c# - 更改 devexpress 网格控件列标题标题

c# - 如何使类似菜单的表单保留在屏幕上所有其他应用程序之上?

java - 如何从我的 LinkedList 中获取数组 []

java - Arraylist - 编译器让我感到困惑

java - 无法使用 JPA 持久保存 HashMap

c# - 您可以更改 ASP.NET Core 项目中 launchSettings.json 的位置吗?