问题描述
鉴于人员类别:
class person
{
public string name;
public int age;
}
说,我重写了类人的GetHashCode方法:
say, i override the class person`s GetHashCode method:
public override int GetHashCode()
{
unchecked
{
hashCode = 17;
// ...some code here...
}
return hashCode;
}
并且基于msdn的指令,我还需要重写Equality,所以我这样做了:
and based on msdn`s instruction, i also need to override the Equality, so i did this:
public override bool Equals(object obj)
{
// ...something like:
return this.name == (person)obj.name && this.age ==(person)obj.age;
}
嘿,等等,我可以得到人实例的哈希码,为什么不仅仅在Equals中使用哈希码呢?像:
hey, wait, sine i can get the hashcode of the person instance, why not just using hashcode in Equals? like:
public override bool Equals(object obj)
{
return this.GetHashCode() == (person)obj.GetHashCode();
}
我在Google上搜索后发现,大多数Equals()示例都与我以前的Equals()版本相似,所以我误会了吗?
i googled and found that most Equals() examples are similar with my previous edition of Equals(), so, am i misunderstood something?
任何帮助,谢谢.
推荐答案
不能保证两个不相等的对象具有不相等的哈希码(称为冲突).这就是 MSDN 说:
Two unequal objects are not guaranteed to have unequal hashcodes (that's called a collision).This is what MSDN says:
如果两个对象比较相等,则每个对象的GetHashCode方法必须返回相同的值.但是,如果两个对象的比较不相等,则两个对象的GetHashCode方法不必返回不同的值.
这篇关于为什么不只在平等中使用GetHashCode?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!