克隆/深度复制 .NET 通用 Dictionary<string, T> 的最佳方法是什么? [英] What is the best way to clone/deep copy a .NET generic Dictionary&lt;string, T&gt;?

查看:30
本文介绍了克隆/深度复制 .NET 通用 Dictionary<string, T> 的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个通用字典 Dictionary 我想基本上制作一个 Clone() 的 ..any 建议.

I've got a generic dictionary Dictionary<string, T> that I would like to essentially make a Clone() of ..any suggestions.

推荐答案

好的,.NET 2.0 的答案:

Okay, the .NET 2.0 answers:

如果您不需要克隆值,您可以使用构造函数重载到字典,它采用现有的 IDictionary.(您也可以将比较器指定为现有字典的比较器.)

If you don't need to clone the values, you can use the constructor overload to Dictionary which takes an existing IDictionary. (You can specify the comparer as the existing dictionary's comparer, too.)

如果您确实需要克隆这些值,您可以使用以下方法:

If you do need to clone the values, you can use something like this:

public static Dictionary<TKey, TValue> CloneDictionaryCloningValues<TKey, TValue>
   (Dictionary<TKey, TValue> original) where TValue : ICloneable
{
    Dictionary<TKey, TValue> ret = new Dictionary<TKey, TValue>(original.Count,
                                                            original.Comparer);
    foreach (KeyValuePair<TKey, TValue> entry in original)
    {
        ret.Add(entry.Key, (TValue) entry.Value.Clone());
    }
    return ret;
}

当然,这依赖于 TValue.Clone() 也是一个合适的深度克隆.

That relies on TValue.Clone() being a suitably deep clone as well, of course.

这篇关于克隆/深度复制 .NET 通用 Dictionary<string, T> 的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆