简体   繁体   English

如何覆盖不带任何数字的GetHashCode()作为字段?

[英]How do I override GetHashCode() without any numbers as fields?

All of the resources showing how to override Equals(object) and GetHashCode() use numeric fields to implement the GetHashCode() method: 所有显示如何重写Equals(object)GetHashCode()使用数字字段来实现GetHashCode()方法:

Implementing the Equals Method 实施平等方法
What's the best strategy for Equals and GetHashCode? Equals和GetHashCode的最佳策略是什么?
Why is it important to override GetHashCode when Equals method is overridden? 当覆盖Equals方法时,覆盖GetHashCode为什么很重要?

However, in my class, I do not have any numeric fields. 但是,在我的课堂上,我没有任何数字字段。 It is a node in a tree with a reference to its parent, children, and an interface as the data: 它是树中的一个节点,引用其父节点,子节点和一个接口作为数据:

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()
    {
        ???
    }
}

What should I set the hashcode with? 我应该用什么设置哈希码?

According to Equals implementation, two Node s instances are equal if and only if their myInterface are equal: 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;
}

That's why myInterface is the only source for GetHashCode : 这就是为什么myInterfaceGetHashCode的唯一来源的原因:

 public override int GetHashCode()
 {
    return null == myInterface ? 0 : myInterface.GetHashCode();
 }

PS ( Edited , thanks to Kris Vandermotten) Often, it's a good practice to check for ReferenceEquals in the Equals implementation before comparing potentially time/resource consuming myInterface s: PS编辑 ,感谢Kris Vandermotten)通常,比较比较可能耗时的myInterface的时间/资源,在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;
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM