1

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

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);
}
4

2 回答 2

2

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

您没有提及GetHashCodem_ownerTreeEquals实施中使用的内容。

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

于 2010-04-25T11:05:05.823 回答
1

A hash algorithm must have the following property:

  • if two things are equal then they have the same hash

A hash algorithm should have the following properties:

  • changing a mutable object does not change its hash code
  • fast
  • never throw an exception
  • small differences between objects should cause large (ideally 50% of the bits) differences in hash code

Does your hash algorithm have the first, necessary property? It doesn't look to me like it does.

于 2010-04-25T14:32:43.063 回答