如果覆盖Equals
总是也覆盖 GetHashCode
.
为什么在重写Equals方法时重写GetHashCode很重要?
这是一个简单的类来演示可能的实现.GetHashCode
应该是有效的,应该产生很少的碰撞:
public class Foo
{
public int ID { get; set; }
public string Name { get; set; }
public override bool Equals(object obj)
{
Foo other = obj as Foo;
if (other == null) return false;
return this.ID == other.ID;
}
public override int GetHashCode()
{
return ID;
}
}
Run Code Online (Sandbox Code Playgroud)
如果您的相等性检查需要包含多个属性或集合,那么这是另一个实现:
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
int hash = 17;
// Suitable nullity checks etc, of course :)
hash = hash * 23 + field1.GetHashCode();
hash = hash * 23 + field2.GetHashCode();
hash = hash * 23 + field3.GetHashCode();
return hash;
}
}
Run Code Online (Sandbox Code Playgroud)