克隆/深度复制.NET泛型字典<string,T>的最佳方法是什么?

我有一个通用字典Dictionary<string, T>,我想基本上做一个克隆()的任何建议。



潇潇雨雨
浏览 716回答 3
3回答

慕姐8265434

好的,.NET 2.0回答:如果您不需要克隆值,则可以使用构造函数重载到Dictionary,它接受现有的IDictionary。(您也可以将比较器指定为现有字典的比较器。)如果确实需要克隆值,可以使用以下内容:public static Dictionary<TKey, TValue> CloneDictionaryCloningValues<TKey, TValue>&nbsp; &nbsp;(Dictionary<TKey, TValue> original) where TValue : ICloneable{&nbsp; &nbsp; Dictionary<TKey, TValue> ret = new Dictionary<TKey, TValue>(original.Count,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; original.Comparer);&nbsp; &nbsp; foreach (KeyValuePair<TKey, TValue> entry in original)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; ret.Add(entry.Key, (TValue) entry.Value.Clone());&nbsp; &nbsp; }&nbsp; &nbsp; return ret;}当然,这也依赖于TValue.Clone()适当的深度克隆。

元芳怎么了

您希望副本有多深,以及您使用的是什么版本的.NET?我怀疑如果您使用的是.NET 3.5,那么对ToDictionary进行LINQ调用(同时指定键和元素选择器)将是最简单的方法。例如,如果您不介意该值是浅层克隆:var newDictionary = oldDictionary.ToDictionary(entry => entry.Key,                                               entry => entry.Value);如果您已经限制T实现ICloneable:var newDictionary = oldDictionary.ToDictionary(entry => entry.Key,                                                entry => (T) entry.Value.Clone());(这些是未经测试的,但应该有效。)

SMILET

Dictionary<string, int> dictionary = new Dictionary<string, int>();Dictionary<string, int> copy = new Dictionary<string, int>(dictionary);
打开App,查看更多内容
随时随地看视频慕课网APP