如果2个数组对象包含相同的值,则生成相同的哈希码

时间:2016-11-22 09:45:38

标签: c# arrays hashcode equality

我正在尝试计算其中一个类的哈希码,问题是:这个类有一个byte [],它为每个对象返回一个不同的哈希值。我已经创建了该类的2个对象,并且都使用新的字节[0]进行实例化。

当覆盖Equals运算符时,我使用了Enumberable.SquenceEqual()来确保两个数组的内容相同。但是,如果数组的内容相同,我如何确保数组返回相同的哈希码呢?

我的代码:

    public override bool Equals(object obj)
    {
        return Equals(obj as MessageType);
    }

    {
        if (messageType != null)
        {
            return (this.Identification == messageType.Identification) &&
                (this.ActivateWindow == messageType.ActivateWindow) &&
                (this.Logging == messageType.Logging) &&
                (Enumerable.SequenceEqual(this.Pictogram, messageType.Pictogram) == true) &&
                (this.Priority == messageType.Priority) &&
                (this.Procedure == messageType.Procedure);
        }

        return false;
    }

    public override int GetHashCode()
    {
        var result = this.Identification != null ? this.Identification.GetHashCode() : 0;
        result = (result * 397) ^ this.ActivateWindow.GetHashCode();
        result = (result * 397) ^ this.Logging.GetHashCode();
        result = (result * 397) ^ ((this.Pictogram != null) ? this.Pictogram.GetHashCode() : 0);
        result = (result * 397) ^ this.Priority.GetHashCode();
        result = (result * 397) ^ ((this.Procedure != null) ? this.Procedure.GetHashCode() : 0);
        return result;
    }

1 个答案:

答案 0 :(得分:1)

据我理解的问题,您应该使用Enumerable.SequenceEqual中的EqualsGetHashCode()中的某种聚合:

   byte[] extraData = ...

   ...

   public bool Equals(MessageType other) {
     ...

     if (!Enumerable.SequenceEqual(extraData, other.extraData))
       return false;

     ...  
   } 

   public override int GetHashCode() {
     unchecked { // we don't want IntegerOverflow exceptions to be thrown
       int result = ...

       ...  
       // let's combine hashes with xor
       result ^= extraData == null 
        ? 0
        : extraData.Aggerate(0, (s, a) => s ^ a); // ...and aggerate with xor as well

       ...

       return result;
     }
   }

如果extraData可能很长(例如,令人震惊的 1 GB ),您可能希望将计算限制为,例如{{1第一项:

10