gpt4 book ai didi

c# - 记录类型 : overriding EqualityContract breaks the equality/hashcode match

转载 作者:行者123 更新时间:2023-12-04 12:32:01 25 4
gpt4 key购买 nike

新引入的记录类型允许覆盖 EqualityContract对于类型,当两个对象相等但具有反对 guidelines 的不同哈希码时,可以创建这种情况。为 GetHashCode覆盖:

If you override the GetHashCode method, you should also override Equals, and vice versa. If your overridden Equals method returns true when two objects are tested for equality, your overridden GetHashCode method must return the same value for the two objects.

    public record Base(string Foo);

public record Child(string Foo, string Bar) : Base(Foo)
{
protected override Type EqualityContract => typeof(Base);
}

var b = new Base("Foo");
var c = new Child("Foo", "Bar");
Console.WriteLine(b == c); // True
Console.WriteLine(b.GetHashCode() == c.GetHashCode()); // False
Child 中删除额外的属性时使 GetHashCodeEquals “比赛”。
显然,这可以通过覆盖 GetHashCode 来解决。 ,但我想知道为什么要覆盖 EqualityContract不会自动导致 GetHashCode返回值“匹配” Equals执行?或者除了手动 GetHashCode之外还有其他方法可以处理吗?覆盖。

最佳答案

正如您在 equality members part of records proposal 中看到的那样,

GetHashCode() returns an int result of a deterministic functioncombining the following values:

  • For each instance field fieldN in the record type that is not inherited, the value ofSystem.Collections.Generic.EqualityComparer<TN>.Default.GetHashCode(fieldN)where TN is the field type, and

  • If there is a base record type, the value of base.GetHashCode(); otherwise the value ofSystem.Collections.Generic.EqualityComparer<System.Type>.Default.GetHashCode(EqualityContract).


因此,在您的示例中 GetHashCodeBase将会
public override int GetHashCode()
{
return EqualityComparer<Type>.Default.GetHashCode(EqualityContract) + EqualityComparer<string>.Default.GetHashCode(Foo);
}
而对于 Child
public override int GetHashCode()
{
return base.GetHashCode() + EqualityComparer<string>.Default.GetHashCode(Bar);
}
对于继承的记录 EqualityContract不用于哈希码计算。如果额外的属性(property) Bar被删除,来自 Base 的值被使用,你会得到一个哈希值相等。因此,覆盖 GetHashCode需要。
使用 sharplab.io 也观察到此行为

关于c# - 记录类型 : overriding EqualityContract breaks the equality/hashcode match,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64864077/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com