字典密钥不包含已包含在密钥中的密钥
问题描述:
为什么以下'exist'布尔变量的值为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);
}
答
你Equals
和GetHashCode
实现做完全不同的事情。他们应该互相镜像。
您在GetHashCode
中没有提及您在Equals
实施中使用的m_ownerTree
。
另外,将哈希码相加并不是计算哈希的最简单的方式。你可能想要把它们(^
)向上。
答
的哈希算法必须具有以下属性:
- 如果两件事情是相等的,那么它们具有相同的哈希
散列算法应该具有以下属性:
- 更改可变对象不会更改其哈希码
- 快速
- 从未抛出异常对象之间
- 小的差异应引起大(位的理想50%)的哈希码的差异
请问您的哈希算法有第一,必要的财产?它不像我这样看待我。
.NET框架文档实际上有一个更好的描述它必须做什么,并澄清你的#1应该做的情况下:http://msdn.microsoft.com/en-us/library/system.object.gethashcode的.aspx – jasonh 2010-04-25 15:59:45