【发布时间】:2013-03-01 11:02:49
【问题描述】:
通过搜索 msdn c# 文档和堆栈溢出,我得到一个清晰的印象,Dictionary<T,T> 应该使用GetHashCode() 来检查键唯一性并进行查找。
Dictionary 泛型类提供从一组键到一组值的映射。字典中的每个添加都包含一个值及其关联的键。使用它的键检索一个值非常快,接近 O(1),因为 Dictionary 类是作为哈希表实现的。 ... 检索的速度取决于为 TKey 指定的类型的散列算法的质量。
我使用单声道(在 Unity3D 中),在我的工作中得到一些奇怪的结果后,我进行了这个实验:
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();
}
}
只有当使用KeyType2 类型时,键才被认为是相等的。对我来说,这表明 Dictionary 使用 Equals(obj) - 而不是 GetHashCode()。
有人可以重现这个,并帮我解释一下是什么意思吗?它是单声道的错误实现吗?还是我误解了什么。
【问题讨论】:
标签: c# generics dictionary comparison unique