字典键不包含已包含在键中的键
为什么以下“存在”布尔变量的值为 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);
}
Why is the following 'exist' boolean variable getting a value of 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);
}
I've overridden GetHashCode() & Equals() Methods as follows:
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);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的
Equals
和GetHashCode
实现做了非常不同的事情。他们应该互相镜像。您在
GetHashCode
中没有提及您在Equals
实现中使用的m_ownerTree
。此外,将哈希码相加并不是计算哈希值的最简单方法。您可能需要对它们进行异或 (
^
)。Your
Equals
andGetHashCode
implementations do very different things. They should be mirroring each other.You have no mention in
GetHashCode
to them_ownerTree
that you are using in yourEquals
implementation.Also, adding up hashcodes is not the bast way of computing a hash. You may want to xor them (
^
) up.哈希算法必须具有以下属性:
算法应该具有以下属性:
您的散列算法是否具有第一个必要的属性?在我看来,它并不像它那样。
A hash algorithm must have the following property:
A hash algorithm should have the following properties:
Does your hash algorithm have the first, necessary property? It doesn't look to me like it does.