所有显示如何覆盖Equals(object)
和GetHashCode()
的资源都使用数字字段来实现GetHashCode()
方法:
Implementing the Equals Method
What's the best strategy for Equals and GetHashCode?
Why is it important to override GetHashCode when Equals method is overridden?
但是,在我的班上,我没有任何数字字段。它是树中的一个节点,引用其父节点,子节点和接口作为数据:
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()
{
???
}
}
我应该用什么设置哈希码?
答案 0 :(得分:7)
根据String s = a==10 ? "true" : "false";
实施,当且仅当System.out.println(s);
相等时,两个Equals
个实例才相等:
Node
这就是为什么myInterface
是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
PS (已编辑,感谢Kris Vandermotten)通常,在GetHashCode
中检查 public override int GetHashCode()
{
return null == myInterface ? 0 : myInterface.GetHashCode();
}
是一种很好的做法在比较潜在的时间/资源消耗ReferenceEquals
之前的实现:
Equals