我正在实现一个对象树.此树中的每个类都有一些属性和GetHashCode()方法.我打算做的是组合所有属性的哈希值,然后将该哈希值与子节点的哈希值结合起来.我现在不在Visual Studio前面,但代码看起来像这样:
class Node
{
public int Prop1 {get; set;}
public string Prop2 {get; set;}
public IEnumerable<Node> Children {get; set; }
private int _hash;
public override int GetHashCode()
{
if (_hash == 0)
{
_hash = 17;
_hash = _hash * 31 + Prop1.GetHashCode();
_hash = _hash * 31 + Prop2.GetHashCode();
foreach(var child in Children)
{
_hash = _hash * 31 + child.GetHasCode();
}
}
return _hash;
}
}
Run Code Online (Sandbox Code Playgroud)
这应该工作但是我担心结束这么大的值,我溢出int 32类型.是否有一种不同的类型可以防止这种情况,但我仍然可以作为一个int返回?我曾经想过使用模数和uint,但我怎么会把它重新转换成有效的int?我可以这样做:
unit _hash = 0;
public override int GetHashCode()
{
// See code above
return (int)((_hash % 4294967295) - int.MaxValue);
}
Run Code Online (Sandbox Code Playgroud)
或者有更好的方法吗?
编码环绕unchecked以抑制整数类算术运算和转换的溢出检查:
public override int GetHashCode()
{
unchecked
{
if (_hash == 0)
{
_hash = 17;
_hash = _hash * 31 + Prop1.GetHashCode();
_hash = _hash * 31 + Prop2.GetHashCode();
foreach(var child in Children)
{
_hash = _hash * 31 + child.GetHasCode();
}
}
return _hash;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
105 次 |
| 最近记录: |