为什么GetHash code()的问题? [英] Why GetHashCode() matters?
问题描述
我想了解一下 object.GetHash code()
的用途。我读了它由集合唯一地标识键。但是,我想进行测试,结果不是我所期待。
结构动物
{
公共字符串名称{;组; }
公众诠释年龄{获得;组; }
公共动物(字符串名称,诠释岁):这个()
{
名称=名称;
年龄=岁;
}
公众覆盖INT GetHash code()
{
返回Age.GetHash code();
}
}
对象狗=新的动物(狗,25);
对象猫=新的动物(猫,25);
哈希表的表=新的Hashtable();
table.Add(狗,狗);
table.Add(猫,猫);
Console.WriteLine({0},表[猫]);
Console.WriteLine({0},表[狗]);
我本来期望猫将覆盖狗或某种错误的认为键已经存在,但输出的是
告诉我猫 狗
GetHash code
仅在第一的支票,用于确定非平等的可能的平等。在此之后,等于被选中。这为对象默认为引用相等,而对于结构是一个成员逐一进行比较。覆盖等于
来给予适当的实现(配对的散列code),它应该给出结果,你希望(重复键)。
顺便说一句,在IDE可能已经给你一个警告, GetHash code
和等于
应始终一起处理......
I am trying to understand what the object.GetHashCode()
is used for. I read that it is used by collections to uniquely identify keys. But I wanted to test this and the result isn't what I expected.
struct Animal
{
public string Name { get; set; }
public int Age { get; set; }
public Animal(string name, int age) : this()
{
Name = name;
Age = age;
}
public override int GetHashCode()
{
return Age.GetHashCode();
}
}
object doggy = new Animal("Dog", 25);
object cat = new Animal("Cat", 25);
Hashtable table = new Hashtable();
table.Add(doggy, "Dog");
table.Add(cat, "Cat");
Console.WriteLine("{0}", table[cat]);
Console.WriteLine("{0}", table[doggy]);
I would have expected "Cat" would overwrite "Dog" or some kind of error telling me that the "key already exists" but the output is
"Cat" "Dog"
GetHashCode
is only the first check, used to determine non-equality and possible equality. After that, Equals is checked. Which for objects defaults to reference-equality, and for structs is a memberwise compare. Override Equals
to give an appropriate implementation (paired with the hash-code), and it should give the results you expect (duplicate key).
btw, the IDE is probably already giving you a warning that GetHashCode
and Equals
should always be treated together...
这篇关于为什么GetHash code()的问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!