【发布时间】:2021-11-07 00:25:07
【问题描述】:
我好像看不懂Hashcode struct的文档:
我尝试了一个天真的:
public struct S : IEquatable<S>
{
public int I { get; set; }
public string[] A { get; set; }
public override bool Equals(object? obj) => obj is S s && Equals(s);
public bool Equals(S other) => I == other.I && StructuralComparisons.StructuralEqualityComparer.Equals(A, other.A);
// public override int GetHashCode() => I.GetHashCode() ^ StructuralComparisons.StructuralEqualityComparer.GetHashCode(A);
public override int GetHashCode() => HashCode.Combine(I, A);
}
导致:
S s1 = new S() { I = 42, A = new string[] { "hello" } };
S s2 = new S() { I = 42, A = new string[] { "hello" } };
Assert.Equal(s1.GetHashCode(), s2.GetHashCode());
给出一个错误:
Xunit.Sdk.EqualException: 'Assert.Equal() Failure Expected: 840823323 Actual: -1160370390'
使用HashCode.Combine 的正确方法是什么(我不喜欢我之前的异或解决方案)?
【问题讨论】: