简体   繁体   English

IEqualityComparer的实现GetHashCode()是什么<double>

[英]What would be implementation GetHashCode() for IEqualityComparer<double>

I am looking for simple implementation of GetHashCode() method for following class. 我正在寻找下面的类的GetHashCode()方法的简单实现。

public class EpsilonEqualityComparer : IEqualityComparer<double>
{
    private readonly double _epsilon;
    public EpsilonEqualityComparer(double epsilon)
    {
        _epsilon = epsilon;
    }

    public bool Equals(double x, double y)
    {
        return Math.Abs(x - y) < _epsilon;
    }

    public int GetHashCode(double obj)
    {
        ...
    }
}

Of course trivial implementation would be something like return Math.Sign(obj) . 当然,简单的实现就像return Math.Sign(obj) Nevertheless I am looking for something more practical. 不过我正在寻找更实用的东西。 Do you have any idea? 你有什么主意吗?

This breaks the specification of IEqualityComparer<> even before you have to worry about GetHashCode . 这甚至在您不必担心GetHashCode之前就打破了IEqualityComparer<>的规范。

For an equality check, you need x == y && y == z to imply x == z but this is not true for your Equals implementation. 对于等式检查,您需要x == y && y == z来暗示x == z但对于您的Equals实现则不然。 For example, with an epsilon of 1 , you have 1 == 1.9 and 1.9 == 2.8 but not 1 == 2.8 . 例如,如果epsilon为1 ,则您有1 == 1.91.9 == 2.8但不是1 == 2.8

(You also require x == x , and x == y to imply y == x , but your equality check is fine with those.) (你还需要x == xx == y来暗示y == x ,但你的相等检查对那些是好的。)

I am afraid my answer to this will be analoguous to this: How to implement GetHashCode for this situation? 我担心我对此的回答与此类似: 如何针对这种情况实现GetHashCode?

However in your case the situation is not so obvious. 但是在你的情况下,情况并不那么明显。 It looks like you have a properly defined equality condition, but it might not be. 看起来你有一个正确定义的相等条件,但它可能不是。

In the other answer I referred to MSDN stating: 在另一个答案中我提到MSDN说:

(x.Equals(y) && y.Equals(z)) returns true if and only if x.Equals(z) returns true. (x.Equals(y)&& y.Equals(z))当且仅当x.Equals(z)返回true时才返回true。

Now, say you have three numbers: 现在,假设您有三个数字:

x = anything
y = x + epsilon
z = y + epsilon // == x + 2 * epsilon

Then x.Equals(y) and y.Equals(z) but x does not equal z . 然后x.Equals(y)y.Equals(z)x不等于z

Because of that you won't end up with properly defined distinct equality sets, and you can't assign those sets any hashcode numbers. 因此,您不会最终得到正确定义的不同的相等集,并且您无法为这些集分配任何哈希码数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM