c# - 覆盖 GetHashCode() 时使用 Guid().GetHashCode() 有什么缺点

标签 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# - 覆盖 GetHashCode() 时使用 Guid().GetHashCode() 有什么缺点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12943590/

相关文章:

c# - 改变 ServiceStack.Text JSON Deserializer 的输出

python dict.fromkeys() 返回空

java - 使用等价运算符还是 equals() 方法来比较字符串的内容更合适?

c# - 在 wpf 中找不到 MainWindow.xaml 文件

c# - 在 javascript 中添加“确定”和“取消”按钮

c# - 模拟对象上的异步回调不等待

c++ - 为什么我的 map 的第二个值没有修改?

python - 获取每个项目的 python dict.keys 轨迹

r - 当使用相等 (==) 的因子对行进行子集化时,还包括 NA。 %in% 不会发生这种情况。正常吗?

java - equals 方法在 java 中不起作用。硬件