简体   繁体   English

是否有内置的IEqualityComparer只使用其哈希值来比较对象?

[英]Is there a built-in IEqualityComparer that compares objects only using their hash value?

Is there a built-in IEqualityComparer that compares objects by the value returned by their GetHashCode value? 是否有内置的IEqualityComparer,它通过GetHashCode值返回的值来比较对象? It's easy to write, but I'd prefer to use a provided class instead of a custom one. 它很容易编写,但我更喜欢使用提供的类而不是自定义的类。

Current code: 当前代码:

private class HashComparer : IEqualityComparer<TKey>
{
    private readonly Func<TKey, int> _Hasher;

    public HashComparer (Func<TKey, int> hasher)
    {
        _Hasher = hasher;
    }

    public bool Equals (TKey x, TKey y)
    {
        // null supposed to throw, therefore no check
        return _Hasher (x) == _Hasher (y);
    }

    public int GetHashCode (TKey obj)
    {
        return _Hasher (obj);
    }
}

No, such a thing doesn't exist in the framework as far as I'm aware. 不,据我所知,框架中不存在这样的事情。

It would be a generally Bad Thing - hash codes don't have to be unique, so it couldn't be used to mimic normal equality, other than for types with 2^32 possible values or fewer, and a hash generation algorithm which gives a unique code for each value. 这通常是Bad Thing - 哈希代码不必是唯一的,因此除了具有2 ^ 32个可能值或更少值的类型之外,它不能用于模仿正常相等,并且哈希生成算法给出每个值的唯一代码。

I'm struggling to think of any sensible use for this - which is why you're unlikely to find it in the framework. 我正在努力想到任何明智的用途 - 这就是为什么你不太可能在框架中找到它。 Perhaps there's some very specialized situation where you'd find it useful, but that's not enough justification to put it in the main framework. 也许有一些非常专业的情况,你会觉得它很有用,但这还不足以将它放在主框架中。

Out of interest, what are you trying to do with it? 出于兴趣,你想用它做什么?

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

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