1

我有以下内容:

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 工作?

4

1 回答 1

3

您的代码看起来像是该问题的答案之一: 您如何在 .NET(特别是 C#)中对对象进行深层复制?

但是,既然您知道字典内容的类型,您就不能手动完成吗?

// 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 使其更紧凑。

于 2010-11-16T01:18:14.703 回答