如何使一个深拷贝词典模板 [英] How to make a deep copy Dictionary template

查看:204
本文介绍了如何使一个深拷贝词典模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下的方法,使一个深拷贝字典的:

I have the following method that makes a deep copy of a dictionary:

public static Dictionary<string, MyClass> deepCopyDic(Dictionary<string, MyClass> src)
{
    //Copies a dictionary with all of its elements
    //RETURN:
    //      = Dictionary copy
    Dictionary<string, MyClass> dic = new Dictionary<string, MyClass>();
    for (int i = 0; i < src.Count; i++)
    {
        dic.Add(src.ElementAt(i).Key, new MyClass(src.ElementAt(i).Value));
    }

    return dic;
}

我在想,我能以某种方式使之成为一个模板?我需要 MyClass的是一个模板。

推荐答案

您可以使用泛型与其中TValue:ICloneable 约束:

You can use Generics with where TValue : ICloneable constraint:

public static Dictionary<TKey, TValue> deepCopyDic<TKey, TValue>(Dictionary<TKey, TValue> src)
    where TValue : ICloneable
{
    //Copies a dictionary with all of its elements
    //RETURN:
    //      = Dictionary copy
    Dictionary<TKey, TValue> dic = new Dictionary<TKey, TValue>();
    foreach (var item in src)
    {
        dic.Add(item.Key, (TValue)item.Value.Clone());
    }

    return dic;
}

您将不得不执行 ICloneable 接口在每一个类,你想传递到该方法。

You'll have to implement ICloneable interface in every class you'd like to pass into that method.

还是有点改良版,与克隆,以及:

Or a bit improved version, with Key cloned as well:

public static Dictionary<TKey, TValue> deepCopyDic<TKey, TValue>(Dictionary<TKey, TValue> src)
    where TValue : ICloneable
    where TKey : ICloneable
{
    return src.ToDictionary(i => (TKey)i.Key.Clone(), i => (TValue)i.Value.Clone());
}

这篇关于如何使一个深拷贝词典模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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