【发布时间】:2010-09-28 05:04:28
【问题描述】:
我在玩字典,偶然发现了以下场景
public class MyObject
{
public string I { get; set; }
public string J { get; set; }
public string K { get; set; }
public override int GetHashCode()
{
int hashCode = (I+J+K).GetHashCode();
Debugger.Log(9, "INFO", hashCode.ToString() + System.Environment.NewLine);
return hashCode;
}
}
class Program
{
static void Main(string[] args)
{
MyObject obj1 = new MyObject() { I = "Hello", J = "World" };
MyObject obj2 = new MyObject() { I = "Hello", J = "World" };
Dictionary<MyObject, string> collection = new Dictionary<MyObject, string>();
collection.Add(obj1, "1");
var result = collection[obj2]; // KeyNotFound exception here.
}
}
我有 MyObject 类,它充当字典的键,我重写 GetHashCode 方法以根据存储在类中的值返回哈希码。
所以,当上面的代码执行时,obj1和obj2都返回相同的哈希码,但是字典仍然抛出KeyNotFound异常。
为什么会出现这种行为?
【问题讨论】:
标签: .net dictionary hashcode