繁体   English   中英

修改字典中的项目而不影响原始对象

[英]Modifying items in dictionary without affecting the original object

我有以下代码:

    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中删除项目也是从测试对象中删除项目。 你能告诉我如何在不影响测试的情况下修改test2中的项目吗?

test2和test是对同一个对象(字典)的相同引用。 为test2实例化一个新字典。

Dictionary<int, int> test2 = new Dictionary<int, int>(test);

当您通过test2 = testtest分配给test2 ,您将分配对该对象的引用 ,这意味着它们都指向内存中的相同位置。 test2上的任何更改都将在test生效。 您需要使用new关键字,例如:

Dictionary<int,int> test2 = new Dictionary<int,int>(test);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM