假设我有以下类和结构定义,并将它们分别用作字典对象中的键:
public class MyClass { }
public struct MyStruct { }
public Dictionary<MyClass, string> ClassDictionary;
public Dictionary<MyStruct, string> StructDictionary;
ClassDictionary = new Dictionary<MyClass, string>();
StructDictionary = new Dictionary<MyStruct, string>();
为什么这是有效的:
MyClass classA = new MyClass();
MyClass classB = new MyClass();
this.ClassDictionary.Add(classA, "Test");
this.ClassDictionary.Add(classB, "Test");
但这在运行时崩溃:
MyStruct structA = new MyStruct();
MyStruct structB = new MyStruct();
this.StructDictionary.Add(structA, "Test");
this.StructDictionary.Add(structB, "Test");
正如预期的那样,它说密钥已经存在,但仅适用于结构。该类将其视为两个单独的条目。我认为这与作为参考与价值的数据有关,但我想更详细地解释原因。