如何制作一个深拷贝字典模板
本文关键字:深拷贝 字典 一个 何制作 | 更新日期: 2023-09-27 18:08:37
我有以下方法,使字典的deep copy
:
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
是一个模板。
您可以使用where TValue : ICloneable
约束的泛型:
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
接口的每一个类,你想传递到该方法。
或者稍微改进的版本,也克隆了Key
:
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());
}
您可以使用复制构造函数选项:
Dictionary<string, int> copy = new Dictionary<string, int>(dictionary);
这样你就得到了字典的深度拷贝。链接到原文
如上所述,序列化方法是唯一的方法。iclonable并不能保证被克隆对象中的所有属性都不分配引用,除非你对对象有完全的控制,这从来都不是一个好的假设,特别是在一个大的团队中。
序列化方法的唯一注意事项是,在字典中传递的所有对象都是可序列化的。此外,序列化并不总是非常有效,因为会发生反射的过度使用,而反射不应该在代码的高性能区域使用。
我使用一种称为快速序列化的方法解决了这个问题,但它要求您计划克隆的所有对象都支持特定的接口。