2010-11-16 59 views
1

我有以下幾點:deepcopy的一個SortedDictionary

SortedDictionary<int, SortedDictionary<int, VolumeInfoItem>> 
,我想deepcopy的

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

+2

請更具體一點,我不能真正告訴你這裏有什麼問題。快速測試表明'DeepClone'按預期工作。 – Diadistis 2010-11-16 01:13:25

回答

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,它也可能會變得更加緊湊。

+0

非常感謝Etienne de Martel。 – user508945 2010-11-16 01:38:07

+0

我將不得不在明天做更多的測試,但似乎運作良好 – user508945 2010-11-16 01:38:33

+1

最後一條評論在上面的代碼中有錯誤。我們應該閱讀:var subCopy = new SortedDictionary (); – user508945 2010-11-16 01:42:37