gpt4 book ai didi

c# - IEqualityComparer GetHashCode 被调用但不等于

转载 作者:可可西里 更新时间:2023-11-01 07:49:20 25 4
gpt4 key购买 nike

我有两个要比较的列表。所以我创建了一个实现 IEqualityComparer 接口(interface)的类,请看下面代码的底部。

当我单步执行我的代码时,代码会通过我的 GetHashCode 实现而不是 Equals?我不太了解 GetHashCode 方法,尽管在 Internet 上四处阅读并了解它到底在做什么。

List<FactorPayoffs> missingfactorPayoffList = 
factorPayoffList.Except(
factorPayoffListOrg,
new FactorPayoffs.Comparer()).ToList();

List<FactorPayoffs> missingfactorPayoffListOrg =
factorPayoffListOrg.Except(
factorPayoffList,
new FactorPayoffs.Comparer()).ToList();

所以在上面的两行代码中,两个列表返回每个项目,告诉我这两个列表不包含任何相同的项目。这不是真的,只有一行不同。我猜这是因为 Equals 方法没有被调用,这反过来让我想知道我的 GetHashCode 方法是否按预期工作?

class FactorPayoffs
{
public string FactorGroup { get; set; }
public string Factor { get; set; }
public DateTime dtPrice { get; set; }
public DateTime dtPrice_e { get; set; }
public double Ret_USD { get; set; }

public class Comparer : IEqualityComparer<FactorPayoffs>
{
public bool Equals(FactorPayoffs x, FactorPayoffs y)
{
return x.dtPrice == y.dtPrice &&
x.dtPrice_e == y.dtPrice_e &&
x.Factor == y.Factor &&
x.FactorGroup == y.FactorGroup;
}

public int GetHashCode(FactorPayoffs obj)
{
int hash = 17;
hash = hash * 23 + (obj.dtPrice).GetHashCode();
hash = hash * 23 + (obj.dtPrice_e).GetHashCode();
hash = hash * 23 + (obj.Factor ?? "").GetHashCode();
hash = hash * 23 + (obj.FactorGroup ?? "").GetHashCode();
hash = hash * 23 + (obj.Ret_USD).GetHashCode();
return hash;
}
}
}

最佳答案

您的EqualsGetHashCode 实现应该包含完全相同的属性集;他们没有。

用更正式的术语来说,GetHashCode必须始终为比较相等的两个对象返回相同的值。使用您当前的代码,仅 Ret_USD 值不同的两个对象将始终比较相等,但不保证具有相同的哈希码。

那么发生的事情是 LINQ 在您认为相等的两个对象上调用 GetHashCode,返回不同的值,得出的结论是,由于值不同,对象不可能相等,因此调用根本没有意义等于 并继续前进。

要解决此问题,请从 GetHashCode 中删除 Ret_USD 因素,或者在 Equals 中也引入它(任何对您的语义有意义的因素)平等)。

关于c# - IEqualityComparer GetHashCode 被调用但不等于,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22453032/

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