编程语言
首页 > 编程语言> > c# – 重写GetHashCode()时使用Guid().GetHashCode()的缺点是什么

c# – 重写GetHashCode()时使用Guid().GetHashCode()的缺点是什么

作者:互联网

我发现GetHashCode()的实现看起来像这样

    Guid _hashCode = Guid.NewGuid();
    public override int GetHashCode()
    {
        return _hashCode.GetHashCode();
    }

即使认为Equals看起来是正确的,说这个实现会导致许多关于.NET的假设破裂是否正确?

       public override bool Equals(object obj)
    {
        if (obj.GetType() != trustedEntity.GetType())
            return false;

        TrustedEntity typedObj = (TrustedEntity)obj;

        if (trustedEntity.BackTrustLink != typedObj.BackTrustLink)
            return false;
        if (trustedEntity.ForwardTrustLink != typedObj.ForwardTrustLink)
            return false;
        if (trustedEntity.EntryName != typedObj.EntryName)
            return false;

        return true;
    }

我听到的反驳论点是,一旦创建了对象,GetHashCode就永远不会改变.这是因为该对象存储在字典中.

有人可以为我清除这一点并解释如果对象发生变化,GetHashCode需要发生什么,最终会改变Equals方法吗?

解决方法:

From MSDN (Notes to Implementers section)

A hash function must have the following properties:

  1. If two objects compare as equal, the GetHashCode method for each
    object must return the same value. However, if two objects do not
    compare as equal, the GetHashCode methods for the two object do not
    have to return different values.

  2. The GetHashCode method for an object must consistently return the
    same hash code as long as there is no modification to the object state
    that determines the return value of the object’s Equals method. Note
    that this is true only for the current execution of an application,
    and that a different hash code can be returned if the application is
    run again.

  3. For the best performance, a hash function must generate a random
    distribution for all input.

根据此对象的Equals方法,您可能也违反了文档中的第一点.

More excellent reading

标签:c,dictionary,equals,gethashcode,iequatable
来源: https://codeday.me/bug/20190629/1331147.html