DeepCopy一个SortedDictionary

时间:2010-11-16 00:57:10

标签: c# deep-copy

我有以下内容:

SortedDictionary<int, SortedDictionary<int, VolumeInfoItem>>

我想深度复印。

VolumeInfoItem是以下类:

[Serializable]
public class VolumeInfoItem
{
    public double up = 0;
    public double down = 0;
    public double neutral = 0;
    public int dailyBars = 0;

}

我创建了以下扩展方法:

public static T DeepClone<T>(this T a)
{
    using (MemoryStream stream = new MemoryStream())
    {
        BinaryFormatter formatter = new BinaryFormatter();
        formatter.Serialize(stream, a);
        stream.Position = 0;
        return (T)formatter.Deserialize(stream);
    }
}

我无法弄清楚如何让deepCopy工作?

1 个答案:

答案 0 :(得分:3)

您的代码看起来像是该问题的答案之一: How do you do a deep copy of an object in .NET (C# specifically)?

但是,既然您知道字典内容的类型,那么您不能手动执行吗?

// assuming dict is your original dictionary
var copy = new SortedDictionary<int, SortedDictionary<int, VolumeInfoItem>>();
foreach(var subDict in dict)
{
    var subCopy = new SortedDictionary<int, VolumeInfoItem>();
    foreach(var data in subDict.Value)
    {
        var item = new VolumeInfoItem
                   {
                       up = data.Value.up,
                       down = data.Value.down,
                       neutral = data.Value.neutral,
                       dailyBars = data.Value.dailyBars
                   };
        subCopy.Add(data.Key, item);
    } 
    copy.Add(subDict.Key, subCopy);
}

在我脑海中编译,因此可能会出现一些语法错误。对于一些LINQ,它也可能更紧凑。