【发布时间】:2022-01-13 02:46:39
【问题描述】:
我当前的解决方案(A, B, C, D, ...).GetHashCode() 是否保证对于具有“相等”项的元组始终相同?
public class Pair
{
public int X { get; set; }
public int Y { get; set; }
public Pair(int x, int y)
{
X = x;
Y = y;
}
public override bool Equals(object other) => Equals(other as Pair);
public virtual bool Equals(Pair other)
{
if (other is null)
{
return false;
}
if (object.ReferenceEquals(this, other))
{
return true;
}
if (this.GetType() != other.GetType())
{
return false;
}
return X == other.X && Y == other.Y;
}
public override int GetHashCode() => (X, Y).GetHashCode();
public static bool operator ==(Pair lhs, Pair rhs)
{
if (lhs is null)
{
if (rhs is null)
{
return true;
}
return false;
}
return lhs.Equals(rhs);
}
public static bool operator !=(Pair lhs, Pair rhs) => !(lhs == rhs);
}
在此代码中始终保证打印1:
var uniquePairs = new HashSet<Pair>();
uniquePairs.Add(new Pair(2, 4));
uniquePairs.Add(new Pair(2, 4));
uniquePairs.Add(new Pair(2, 4));
uniquePairs.Add(new Pair(2, 4));
Console.WriteLine(uniquePairs.Count);
如果有更多的非平凡类型属性呢?
有哪些可靠的GetHashCode 解决方案可用于此类类,如果所有(非必要的整数)成员都相同,则可以保证相同的哈希值?
【问题讨论】:
-
not 哈希码不是永久值
-
@LeiYang 是否在运行时之间保留哈希码无关
-
我认为在您的用例中哈希码是可靠的(所有事情只发生在一个进程中)。实际上,这是许多复合对象获取哈希码的方式。
-
@LeiYang 我以前经常看到这种模式,但是this answer“结合每个对象的哈希码(和一个额外的随机种子)”让我想检查
-
如果你指的是微软的实现,我认为他们避免使用
GetHashCode以获得更好的性能。
标签: c# .net-standard-2.0