本文介绍了通用的IEqualityComparer< T>和GetHashCode的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

来有些懒惰有关实现大量IEqualityComparers的,鉴于我无法轻松地编辑对象的类实现被比较,我去以下,意味着与鲜明的()和除()扩展方法使用。

Being somewhat lazy about implementing lots of IEqualityComparers, and given that I couldn't easily edit class implementations of object being compared, I went with the following, meant to be used with Distinct() and Except() extension methods. :

public class GenericEqualityComparer<T> : IEqualityComparer<T>
{
    Func<T, T, bool> compareFunction;
    Func<T, int> hashFunction;

    public GenericEqualityComparer(Func<T, T, bool> compareFunction, Func<T, int> hashFunction)
    {
        this.compareFunction = compareFunction;
        this.hashFunction = hashFunction;
    }

    public bool Equals(T x, T y)
    {
        return compareFunction(x, y);
    }

    public int GetHashCode(T obj)
    {
        return hashFunction(obj);
    }
}



似乎不错,但实在是给人一种散列函数everytimes有必要吗?
我明白的哈希码是用来放对象桶。不同的水桶,对象不相等,且等于不叫。

Seems nice, but is giving an hash function everytimes REALLY necessary ? I understand that the hashcode is used to put objects in buckets. Different buckets, object are not equal, and equal is not called.

如果GetHashCode返回相同的值,等于被调用。 (来源:为什么是重要的,当equals方法在C#中被重写重写GetHashCode?

If GetHashCode returns the same value, equals is called. ( from : Why is it important to override GetHashCode when Equals method is overriden in C#? )

那么,什么可能出错,例如,如果(我听到很多程序员惊恐尖叫),G​​etHashCode返回一个常数,以强制调用平等?

So what could go wrong, if for example (and I hear a lot of programmers screaming in horror), GetHashCode returns a constant, to force the call to Equal ?

推荐答案

不会有事,但在基于散列的表箱,你从约O(1)进行查找时要O(n)性能。你会更好只是存储在一个列表的一切,蛮力搜索这对于实现平等的项目。

Nothing would go wrong, but in hash-table based containers, you're going from approx O(1) to O(n) performance when doing a lookup. You'd be better off simply storing everything in a List and brute force searching it for items that fulfil equality.

这篇关于通用的IEqualityComparer&LT; T&GT;和GetHashCode的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!