我有以下方法制作字典的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
作为模板。
答案 0 :(得分:6)
您可以将Generics与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());
}
答案 1 :(得分:2)
您可以使用复制构造函数选项:
Dictionary<string, int> copy = new Dictionary<string, int>(dictionary);
通过这种方式,您可以复制字典。 Link原帖。
答案 2 :(得分:1)
如上所述,序列化方法是唯一的方法。 ICloneable并不保证被克隆对象中的所有属性都不会分配引用,除非您完全控制对象,这绝不是一个好的假设,尤其是在大型团队中。
序列化方法的唯一要点是在字典中传递的所有对象都是可序列化的。此外,序列化并不总是非常有效,因为过度使用了反射,不应该在高性能代码区域中使用。
我使用称为快速序列化的方法解决了这个问题,但它要求您计划克隆的所有对象都支持特定的接口。它始终是速度与复杂性。