如何覆盖没有任何数字作为字段的GetHashCode()?

Evo*_*lor 1 c# equality hashcode iequalitycomparer gethashcode

所有资源显示如何覆盖Equals(object)GetHashCode()使用数字字段来实现该GetHashCode()方法:

实现Equals方法
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()
    {
        ???
    }
}
Run Code Online (Sandbox Code Playgroud)

我应该用什么设置哈希码?

Dmi*_*nko 7

根据Equals实现,Node当且仅当它们myInterface相等时,两个s实例是相等的:

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;
}
Run Code Online (Sandbox Code Playgroud)

这就是为什么myInterface唯一的来源GetHashCode:

 public override int GetHashCode()
 {
    return null == myInterface ? 0 : myInterface.GetHashCode();
 }
Run Code Online (Sandbox Code Playgroud)

PS(编辑,感谢Kris Vandermotten)通常,在比较潜在的时间/资源消耗之前ReferenceEquals,在Equals实现中检查是一个好习惯myInterface:

 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;
 }
Run Code Online (Sandbox Code Playgroud)