在IComparer的情况下,哪个GetHashcode将占主导地位

时间:2014-04-09 06:01:46

标签: c# .net linq

我遇到以下情况

class Custom
{
    public override int GetHashCode(){...calculation1}
}

public class MyComparer : IEqualityComparer<Custom>
{
    public bool Equals(Custom cus1, Custom cus2)
    {
        if (cus1 == null || cus2 == null)
            return false;

        return cus1.GetHashCode() == cus2.GetHashCode();
    }

    public int GetHashCode(Custom cus1)
    {
        return ...calculation2;
    }
}

int Main()
{
    List<Custom> mine1 = new List<Custom>(){....};
    List<Custom> mine2 = new List<Custom>(){....};
    MyComparer myComparer = new MyComparer();
    List<Custom> result = mine1.intersect(mine2,myComparer);
}

这里我想知道哪个GetHashCode将用于交叉。

3 个答案:

答案 0 :(得分:1)

要回答你的问题,它将是来自MyComparer的GetHashCode。

但是,有一个非常重要的原因,即 GetHashCode Equals 方法。 GetHashCode()是一种优化,因此在最初比较项目时,只检查哈希码,如果哈希码相同,则使用Equals方法。这避免了不同物体出现相同哈希的可能性(机会是大约4亿个,但它仍然会发生,从第一个人看来)。在 Equals()方法中,您应该比较一个对象与另一个对象的所有相关字段。在Equals中通过哈希码比较对象是错误的,并且违背了该方法的整个目的。

希望澄清。

答案 1 :(得分:0)

你为什么不自己测试一下?你已经有了代码......

MyComparer.GetHashCode将用于您的情况。您可以在此处查看代码:http://referencesource.microsoft.com/#System.Core/System/Linq/Enumerable.cs#f4105a494115b366

如果您未在Custom.GetHashCode来电时指定比较器,则会使用

Intersect

答案 2 :(得分:0)

通常,哈希代码和getHashCode函数提供了一个很好的比较机制,但你应该注意相似性。由于散列设备支持的范围有限,很常见的是两个不同的数字导致相同的散列码,这可能会干扰比较上下文。