Skip to main content
 首页 » 编程设计

c#之ToDictionary() 是否创建副本或引用

2024年02月05日10落叶

关于 ToDictionary() 的 MSDN 文档并没有多说它实际上是如何工作的。我想知道它是创建字典及其元素的副本,还是只是重复使用相同的引用和枚举器。

例如,如果我有一个 ConcurrentDictionary c,并且我通过调用 c.ToDictionary(...) 创建了一个 Dictionary d ,我可以使用(想想 foreach)d 独立地(以线程安全的方式)更新 c 的线程吗?

事实上,当我这样做时,我得到:

Collection was modified; enumeration operation may not execute.

...序列化 d 时。

请您参考如下方法:

Enumerable.ToDictionary创建您的集合的浅拷贝。

您可以在 .NET Reference source 中看到此行为:

public static Dictionary<TKey, TElement> ToDictionary<TSource, TKey, TElement>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, Func<TSource, TElement> elementSelector, IEqualityComparer<TKey> comparer) 
{ 
    if (source == null) throw Error.ArgumentNull("source"); 
    if (keySelector == null) throw Error.ArgumentNull("keySelector"); 
    if (elementSelector == null) throw Error.ArgumentNull("elementSelector"); 
    Dictionary<TKey, TElement> d = new Dictionary<TKey, TElement>(comparer); 
    foreach (TSource element in source) d.Add(keySelector(element), elementSelector(element)); 
    return d; 
} 

如您所见,它创建了一个新的 Dictionary,遍历您的集合并将所有元素添加到其中,应用选择器函数。因此,如果您更新原始集合,词典将不会更新,反之亦然。