這個問題來自tuples的討論。c#如何找出對象的哈希碼?
我開始考慮元組應該擁有的哈希碼。 如果我們將KeyValuePair類作爲一個元組接受,該怎麼辦?它不重寫GetHashCode()方法,所以它可能不會意識到它的「孩子」的哈希碼......所以,運行時將調用Object.GetHashCode(),它不知道真實的物體結構。
然後,我們可以製作兩個實例,因爲重載的GetHashCode()和Equals(),它們實際上是Equal。並用它們作爲元組中的「孩子」來「欺騙」字典。
但它不起作用!運行時以某種方式計算出我們元組的結構並調用我們類的重載GetHashCode!
它是如何工作的? Object.GetHashCode()做了什麼分析?
當我們使用一些複雜的按鍵時,會不會影響性能? (可能是不可能的場景......但還是)
考慮以下代碼爲例:
namespace csharp_tricks
{
class Program
{
class MyClass
{
int keyValue;
int someInfo;
public MyClass(int key, int info)
{
keyValue = key;
someInfo = info;
}
public override bool Equals(object obj)
{
MyClass other = obj as MyClass;
if (other == null) return false;
return keyValue.Equals(other.keyValue);
}
public override int GetHashCode()
{
return keyValue.GetHashCode();
}
}
static void Main(string[] args)
{
Dictionary<object, object> dict = new Dictionary<object, object>();
dict.Add(new KeyValuePair<MyClass,object>(new MyClass(1, 1), 1), 1);
//here we get the exception -- an item with the same key was already added
//but how did it figure out the hash code?
dict.Add(new KeyValuePair<MyClass,object>(new MyClass(1, 2), 1), 1);
return;
}
}
}
更新我想我找到了在我的答案在下面說明該解釋。它的主要成果是:
- 小心你的鑰匙和他們的哈希碼:-)
- 對於複雜的字典鍵,你必須正確地重寫的equals()和GetHashCode()。
這種解釋與代碼示例矛盾的問題。 – 2008-09-19 15:47:28