2010-04-14 54 views
1

鑑於以下代碼:.NET Hashtable的克隆

Hashtable main = new Hashtable(); 

Hashtable inner = new Hashtable(); 
ArrayList innerList = new ArrayList(); 
innerList.Add(1); 
inner.Add("list", innerList); 

main.Add("inner", inner); 

Hashtable second = (Hashtable)main.Clone(); 
((ArrayList)((Hashtable)second["inner"])["list"])[0] = 2; 

爲什麼從1中的「主」哈希表的陣列變化到2內的值作爲變化上的克隆製成?

回答

0

感謝您的幫助,夥計們。我結束了這個解決方案:

Hashtable clone(Hashtable input) 
{ 
    Hashtable ret = new Hashtable(); 

    foreach (DictionaryEntry dictionaryEntry in input) 
    { 
     if (dictionaryEntry.Value is string) 
     { 
      ret.Add(dictionaryEntry.Key, new string(dictionaryEntry.Value.ToString().ToCharArray())); 
     } 
     else if (dictionaryEntry.Value is Hashtable) 
     { 
      ret.Add(dictionaryEntry.Key, clone((Hashtable)dictionaryEntry.Value)); 
     } 
     else if (dictionaryEntry.Value is ArrayList) 
     { 
      ret.Add(dictionaryEntry.Key, new ArrayList((ArrayList)dictionaryEntry.Value)); 
     } 
    } 

    return ret; 
} 
+0

這可能適合您的情況,但請注意,ArrayList仍然是淺層克隆的。如果數組列表包含對象,那麼這裏仍然存在不規則的深度+淺層克隆。 – 2010-04-14 08:21:01

+3

看起來像一個擴展方法的體面的候選人。 – 2010-04-14 08:27:00

5

您克隆了Hashtable,而不是其內容。

+0

感謝您的提示。我也嘗試了一個新的Hashtable(main),它仍然是一樣的。你能否建議一個合適的方法?謝謝。 – thelost 2010-04-14 07:41:18

+5

如果您想要進行深度克隆,您必須通過迭代原始集合,克隆每個項目並將其插入到一個新集合(您必須創建爲空)來手動完成。 – 2010-04-14 07:44:43