【发布时间】:2013-05-04 13:00:19
【问题描述】:
假设我有以下类和结构定义,并将它们分别用作字典对象中的键:
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");
它说密钥已经存在,正如预期的那样,但仅适用于结构。该类将其视为两个单独的条目。我认为这与作为参考与价值的数据有关,但我想更详细地解释原因。
【问题讨论】:
-
你忽略了
classA、classB、structA和structB是什么。你能添加那个代码吗? -
您没有显示实例的来源,但无论哪种方式,对于您打算用作键的类,您都希望覆盖 GetHashCode 和 Equals 方法。
-
已添加实例定义。谢谢!
标签: c# class dictionary struct equality