通過搜索雖然MSDN C#的文件和堆棧溢出,我得到了清晰的印象是Dictionary<T,T>
應該使用GetHashCode()
檢查密鑰的唯一性和做查找。單執行字典<T,T>使用.Equals的(OBJ O)代替.GetHashCode()
Dictionary泛型類提供了從一組鍵到一組值的映射。字典中的每個添加項都包含一個值及其關聯的鍵。使用其鍵值檢索值非常快,接近O(1),因爲Dictionary類是作爲散列表實現的。 ... 檢索速度取決於爲TKey指定的類型的哈希算法的質量。當使用
public class DictionaryTest { public static void TestKeyUniqueness() { //Test a dictionary of type1 Dictionary<KeyType1, string> dictionaryType1 = new Dictionary<KeyType1, string>(); dictionaryType1[new KeyType1(1)] = "Val1"; if(dictionaryType1.ContainsKey(new KeyType1(1))) { Debug.Log ("Key in dicType1 was already present"); //This line does NOT print } //Test a dictionary of type1 Dictionary<KeyType2, string> dictionaryType2 = new Dictionary<KeyType2, string>(); dictionaryType2[new KeyType2(1)] = "Val1"; if(dictionaryType2.ContainsKey(new KeyType2(1))) { Debug.Log ("Key in dicType2 was already present"); // Only this line prints } } }
//This type implements only GetHashCode() public class KeyType1 { private int var1; public KeyType1(int v1) { var1 = v1; } public override int GetHashCode() { return var1; } }
//This type implements both GetHashCode() and Equals(obj), where Equals uses the hashcode. public class KeyType2 { private int var1; public KeyType2(int v1) { var1 = v1; } public override int GetHashCode() { return var1; } public override bool Equals (object obj) { return GetHashCode() == obj.GetHashCode(); } }
只有:
我使用單(在Unity3D),並得到了一些奇怪的結果在我的工作後,我進行了這項實驗類型KeyType2
是被認爲相同的關鍵。對我來說,這表明Dictionary使用Equals(obj) - 而不是GetHashCode()。
有人可以重現這一點,並幫助我解釋的意思是?這是單聲道不正確的實現嗎?或者我誤解了一些東西。
MSDN還聲明: 「Dictionary泛型類提供了從一組鍵到一組值的映射。由一個值及其相關的鍵組成,使用它的鍵檢索值非常快,接近於O(1),因爲Dictionary 類是作爲散列表實現的。「 我把它解釋爲這意味着散列用於唯一性和查找。 –
sune
2013-03-01 11:39:37
@sune它僅用於查找。正如名字所說,'GetHasCode'只是一個幫助排序項目以加快查找的散列。有關'GetHashCode'的用法,請參閱http://stackoverflow.com/questions/7425142/what-is-hashcode-use-for-is-it-unique。 – ken2k 2013-03-01 12:24:25
感謝您的回答。 – sune 2013-03-01 12:30:58