如何覆盖GetHashCode()而不将任何数字作为字段?
显示如何覆盖Equals(object)
和GetHashCode()
所有资源都使用数字字段来实现GetHashCode()
方法:
实施等式方法
Equals和GetHashCode的最佳策略是什么?
当Equals方法被覆盖时为什么重写GetHashCode很重要?
但是,在我的班级中,我没有任何数字字段。 它是树中的一个节点,引用它的父节点,子节点和接口作为数据:
public class Node
{
private IInterface myInterface;
private Node parent;
private List<Node> children = new List<Node>();
public override bool Equals(object obj)
{
if (obj == null || GetType() != obj.GetType())
{
return false;
}
var node = (Node)obj;
return myInterface == node.myInterface;
}
public override int GetHashCode()
{
???
}
}
我应该如何设置哈希码?
根据Equals
实现,当且仅当它们的myInterface
相等时,两个Node
的实例才是相等的:
public override bool Equals(object obj)
{
if (obj == null || GetType() != obj.GetType())
{
return false;
}
var node = (Node)obj;
// instances are equal if and only if myInterface's are equal
return myInterface == node.myInterface;
}
这就是为什么myInterface
是GetHashCode
的唯一来源:
public override int GetHashCode()
{
return null == myInterface ? 0 : myInterface.GetHashCode();
}
PS ( 编辑 ,感谢Kris Vandermotten)通常,在比较可能耗费时间/资源的myInterface
s之前,在Equals
实现中检查ReferenceEquals
是一种很好的做法:
public override bool Equals(object obj) {
// Easy tests:
// 1. If "this" and "obj" are in fact just the same reference?
// 2. Since `Node` (or Equals) is not sealed, the safiest is to check types
if (object.ReferenceEquals(this, obj))
return true;
else if (null == obj || other.GetType() != GetType())
return false;
// Potentially time/resource cosuming (we don't know IInterface implementation)
return ((Node) obj).myInterface == myInterface;
}
链接地址: http://www.djcxy.com/p/39789.html
上一篇: How do I override GetHashCode() without any numbers as fields?