ToDictionary()上的 MSDN 文档并没有说明它的实际工作方式。我想知道它是否创建了字典及其元素的副本,或者只是重用了相同的引用和枚举器。
例如,如果我有一个 ConcurrentDictionary c,并且我d通过调用创建了一个 Dictionary c.ToDictionary(...),我是否可以独立地(以线程安全的方式)使用(思考foreach)d线程更新c吗?
事实上,当我这样做时,我得到:
集合被修改;枚举操作可能无法执行。
...当序列化d.
Enumerable.ToDictionary 创建您收藏的浅表副本。
您可以在.NET 参考源中看到此行为:
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;
}
Run Code Online (Sandbox Code Playgroud)
如您所见,它创建了一个 new Dictionary,遍历您的集合并将所有元素添加到其中,应用选择器函数。因此,如果您更新原始集合,则字典不会更新,反之亦然。