ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

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

2019-06-29 23:52:54  阅读:853  来源: 互联网

标签:c dictionary equals gethashcode iequatable


我发现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

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有