【问题标题】:Dictionary keys don't contain a key that's already contained in keys字典键不包含键中已包含的键
【发布时间】:2011-02-12 01:40:25
【问题描述】:

为什么以下“存在”布尔变量的值为 false???

foreach (Cell existCell in this.decoratorByCell.Keys)
{   
            //this call yield the same hashcode for both cells. still exist==false
            bool exist =
                this.decoratorByCell.ContainsKey(existCell);
}

我已经重写了 GetHashCode() 和 Equals() 方法,如下所示:

public override int GetHashCode()
{
            string nodePath = GetNodePath();

            return nodePath.GetHashCode() + m_ownerColumn.GetHashCode();
}

public bool Equals(Cell other)
{
bool nodesEqual = (other.OwnerNode == null && this.OwnerNode == null) || (other.GetNodePath() == this.GetNodePath());
bool columnsEqual = (other.OwnerColumn == null && this.OwnerColumn == null) || (other.OwnerColumn == this.OwnerColumn);
bool treesEqual = (this.m_ownerTree == other.m_ownerTree);

return (nodesEqual && columnsEqual && treesEqual);
}

【问题讨论】:

    标签: c# dictionary key gethashcode equals-operator


    【解决方案1】:

    您的EqualsGetHashCode 实现做了非常不同的事情。它们应该相互镜像。

    您在GetHashCode 中没有提及您在Equals 实现中使用的m_ownerTree

    此外,将哈希码相加并不是计算哈希的糟糕方法。您可能想对它们进行异或 (^)。

    【讨论】:

      【解决方案2】:

      哈希算法必须具有以下属性:

      • 如果两个事物相等,则它们具有相同的哈希

      哈希算法应该具有以下属性:

      • 更改可变对象不会更改其哈希码
      • 从不抛出异常
      • 对象之间的微小差异应该会导致哈希码的大差异(理想情况下是 50% 的位)

      您的哈希算法是否具有第一个必要的属性?在我看来它不像它。

      【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-09-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-08
      • 1970-01-01
      • 2021-01-21
      • 2018-01-18
      相关资源
      最近更新 更多