[英]How do I create a copy of a Dictionary<int,List<int>> without affecting the original (C#)?
[英]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 = test
将test
分配给test2
,您将分配对该对象的引用 ,这意味着它们都指向内存中的相同位置。 test2
上的任何更改都将在test
生效。 您需要使用new
关键字,例如:
Dictionary<int,int> test2 = new Dictionary<int,int>(test);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.