c# - 复制字典的意外结果

标签 c# .net dictionary

这违背了我对复制字典的理解。比如说,我有以下代码:

public class MyClass
{
    public string str1;

    public MyClass(string s)
    {
        str1 = s;
    }
}

Dictionary<string, MyClass> dic1 = new Dictionary<string, MyClass>();
dic1.Add("0", new MyClass("hello"));

//Make 'dic2' as a copy of 'dic1'
Dictionary<string, MyClass> dic2 = new Dictionary<string, MyClass>(dic1);

//Alter 'dic1'
dic1.ElementAt(0).Value.str1 += "!!!";

//I was expecting dic2 not to be altered, but IT IS!
Debug.Assert(dic2["0"].str1.Equals(dic1["0"].str1, StringComparison.Ordinal) == false);     //Result is true for equality

我原以为更改复制的字典不会更改原始字典,但我的代码并非如此。

我做错了什么?

最佳答案

正如 Corak 所说,你已经制作了一个浅拷贝。您正在复制对内存中对象的引用,而不是对象本身。现在,对于每个键,您都有对一个对象的两个引用。

您想要的是深层复制,请参见此处:What is the best way to clone/deep copy a .NET generic Dictionary<string, T>?

关于c# - 复制字典的意外结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15946192/

相关文章:

javascript - 在 Visual Studio Code 上使用空格、括号或句点触发 Intellisense 自动完成

c# - 如何向图像添加 JPEG 注释 (COM)?

javascript - 使用 Javascript 的 HiddenFields 中的空值

c# - 我如何判断我的程序是否是焦点程序?

c# - 为什么将委托(delegate)声明为静态会导致编译器错误 "The modifier ' static' is not valid for this item”?

dictionary - 在 Kotlin 中将 `Throwable?` 映射到 `Result<Unit>`

c# - 带有javascript确认功能的必填字段验证器未验证

.net - 我们需要关闭 System.Net.WebRequest 的 ResponseStream 吗?

.net - HashSet<T> 与 Dictionary<K, V> 相对于查找项目是否存在的搜索时间

C++ 如何打印和(访问) vector 元组(在 map 中)?