【发布时间】:2014-03-17 11:23:38
【问题描述】:
我有两个要比较的列表。所以我创建了一个实现IEqualityComparer 接口的类,请参见下面的代码底部部分。
当我单步执行我的代码时,代码会通过我的 GetHashCode 实现而不是 Equals?我并不真正了解GetHashCode 方法,尽管在互联网上阅读以及它到底在做什么。
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;
}
}
}
【问题讨论】:
-
当两个实例被认为相等时,
GetHashCode实现必须返回相同的值。当它们不相等时,它应该尝试返回不同的数字,但这并不重要。
标签: c#