2

次のコードがあります。

    Dictionary<int, int> test = new Dictionary<int, int>();
    test.Add(1,1);
    test.Add(2, 2);

    Dictionary<int, int> test2 = test;
    test2.Remove(1);

test2からアイテムを削除すると、テストオブジェクトからもアイテムが削除されます。testに影響を与えずにtest2の項目を変更する方法を教えてください。

4

2 に答える 2

5

test2 と test は、同じオブジェクト (辞書) への同じ参照です。test2 の新しい辞書をインスタンス化します。

Dictionary<int, int> test2 = new Dictionary<int, int>(test);
于 2012-07-19T11:59:35.747 に答える
4

viaに割り当てるtestと、そのオブジェクトへの参照が割り当てられます。つまり、両方ともメモリ内の同じ場所を指します。での変更は で有効になります。次のようなキーワードを使用する必要があります。test2test2 = testtest2testnew

Dictionary<int,int> test2 = new Dictionary<int,int>(test);
于 2012-07-19T12:00:28.030 に答える