4

ハッシュテーブルの浅いコピーと深いコピーに関するいくつかの記事/説明に出くわしました。読むほど、混乱します。

Hashtable ht = new Hashtable();
ht.Add("1", "hello");

Hashtable ht2 = new Hashtable();
ht2 = ht;                          // case1: is this shallow copy?
ht2["1"] = "H2";

Hashtable ht3 = new Hashtable(ht); // case2: is this shallow copy?
ht3["1"] = "H3";

Hashtable ht4 = new Hashtable();
ht4 = (Hashtable)ht.Clone();       // case3: is this shallow copy?
ht4["1"] = "H4";
  • ケース1:結果、htコンテンツの変更はht2と同じになります。
  • ケース2:結果、htコンテンツはht3とは異なります。
  • ケース3:結果、htコンテンツはht4とは異なります。

Case2とCase3が浅いコピーの場合、結果はCase1と同じではないでしょうか。

これはList、ArrayListなどにも起こりますか?

4

1 に答える 1

2

ケース1の場合、とは両方ともht2ht同じインスタンスを参照しますHashtable

ケース2と3の場合、元のエントリをコピーして作成されたさまざまなオブジェクトht3ht4参照します。Hashtable

「ディープ」コピーを作成する(新しいマッピングを作成する)場合でも、参照をコピーしていることに注意してください。したがって、たとえば:

var original = new Dictionary<int, StringBuilder>();
original[10] = new StringBuilder();

var copy = new Dictoinary<int, StringBuilder>(original);
copy[20] = new StringBuilder();

// We have two different maps...
Assert.IsFalse(original.ContainsKey(20));

// But they both refer to a single StringBuilder in the entry for 10...
copy[10].Append("Foo");
Assert.AreEqual("Foo", original[10].ToString());
于 2012-07-19T11:17:47.837 に答える