关于ToDictionary()的MSDN文档并未详细说明其实际工作方式。我想知道它是创建字典及其元素的副本,还是仅重用相同的引用和枚举器。
举例来说,如果我有一个ConcurrentDictionary c
,和我创建了一个词典d
调用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;
}
如您所见,它将创建一个new Dictionary
,对您的集合进行迭代,并应用选择器功能将所有元素添加到其中。因此,如果您更新原始收藏,则字典将不会更新,反之亦然。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句