How to impelement GetHashCode in class without any ID

This question already has an answer here:

  • What is the best algorithm for an overridden System.Object.GetHashCode? 17 answers
  • Implementing GetHashCode correctly [duplicate] 1 answer

  • 您应该将您的对象的哈希码计算基于不可变字段,如果您可以使Person的FirstName和LastName字段不可变,则可以使用基于Josh Bloch建议的以下模式:

    public override int GetHashCode()
    {
        int hash = 17;
        hash = hash * 31 + FirstName.GetHashCode();
        hash = hash * 31 + LastName.GetHashCode();
        return hash;
    }
    

    public override int GetHashCode()
        {
            return String.Concat(FirstName, LastName).GetHashCode();
        }
    

    You can do something like this:

    public override int GetHashCode()
    {
        return FirstName.GetHashCode() ^ LastName.GetHashCode()
    }
    

    Check this for more

    链接地址: http://www.djcxy.com/p/39778.html

    上一篇: GetHashCode覆盖包含泛型数组的对象

    下一篇: 如何在没有任何ID的情况下在类中强制GetHashCode