的IEqualityComparer<双>容忍;如何实现GetHashCode? [英] IEqualityComparer<double> with a tolerance; how to implement GetHashCode?
问题描述
我正在实现一个可重用的DoubleEqualityComparer(具有自定义容差:epsilon构造函数参数),以缓解LINQ的使用顺序为双倍。例如:
I'm implementing a reusable DoubleEqualityComparer (with a custom tolerance: the "epsilon" constructor parameter) to ease the usage of LINQ with sequences of double. For example:
bool myDoubleFound = doubles.Contains(myDouble, new DoubleEqualityComparer(epsilon: 0.01));
实现GetHashCode的正确方法是什么?以下是代码:
What is the right way to implement GetHashCode? Here's the code:
public class DoubleEqualityComparer : IEqualityComparer<double>, IEqualityComparer<double?>
{
private readonly double epsilon;
public DoubleEqualityComparer(double epsilon)
{
if (epsilon < 0)
{
throw new ArgumentException("epsilon can't be negative", "epsilon");
}
this.epsilon = epsilon;
}
public bool Equals(double x, double y)
{
return System.Math.Abs(x - y) < this.epsilon;
}
public int GetHashCode(double obj)
{
// ?
}
}
PS:我总是可以返回相同的值:GetHashCode(double obj){return 0;})总是强制调用Equals(double,double)方法(不是很好的,我知道),但是我记得这个解决方案会在比较器与字典一起使用时产生问题...
PS: I can always return the same value (ex: GetHashCode(double obj){ return 0; }) to always force the call to Equals(double, double) method (not very performant, I know), but I remember that this solution causes problems when the comparer is used with a dictionary...
推荐答案
我不知道使用EqualityComparer是如何去的。因为比较的对象不等于。
I'm not sure using EqualityComparer is the way to go. Because compared objects are not equals.
也许您应该考虑使用简单的任何
子句+实用程序方法:
Maybe you should consider using a simple Any
clause + an utility method :
private static bool DoublesAreNearlyEquals(double d1, double d2, double epsilon = 0.01D)
{
return System.Math.Abs(d1 - d2) < this.epsilon;
}
private void foo()
{
var myDoubles = Getdoubles();
var doubleToSearch = 42D;
var result = myDoubles.Any(d=>DoublesAreNearlyEquals(d, doubleToSearch));
}
这篇关于的IEqualityComparer<双>容忍;如何实现GetHashCode?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!