Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 对于IComparer,哪个GetHashcode将占主导地位_C#_.net_Linq - Fatal编程技术网

C# 对于IComparer,哪个GetHashcode将占主导地位

C# 对于IComparer,哪个GetHashcode将占主导地位,c#,.net,linq,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) r

我有以下情况

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);
}
类自定义
{
公共重写int GetHashCode(){…calculation1}
}
公共类MyComparer:IEqualityComparer
{
公共布尔等于(自定义cus1、自定义cus2)
{
if(cus1==null | | cus2==null)
返回false;
返回cus1.GetHashCode()==cus2.GetHashCode();
}
public int GetHashCode(自定义cus1)
{
返回…计算2;
}
}
int Main()
{
List mine1=新列表(){..};
List mine2=新列表(){..};
MyComparer MyComparer=新的MyComparer();
列表结果=mine1.intersect(mine2,myComparer);
}

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

为什么不自己测试它?你已经有密码了

MyComparer.GetHashCode
将用于您的案例。您可以在此处看到代码:


Custom.GetHashCode
如果您根本没有在
Intersect
调用中指定比较器,则将使用它。

通常,哈希代码和GetHashCode函数提供了一种很好的比较机制,但您应该注意相似性。由于哈希工具支持的范围有限,两个不同的数字在同一个哈希代码中产生的结果很常见,这可能会干扰比较上下文。

要回答您的问题,请从MyComparer获取哈希代码

但是,有一个非常重要的原因,为什么会有一个GetHashCode和一个Equals方法GetHashCode()是一种优化,因此在最初比较项目时,只检查哈希代码,如果哈希代码相同,则使用Equals方法。这避免了对不同对象使用相同哈希的可能性(这种可能性是~4bilions中的一个,但这种情况仍然会发生,请第一人称看到)。在Equals()方法中,您应该将一个对象的所有相关字段与另一个对象进行比较。在Equals中用hashcode比较对象是错误的,违背了此方法的全部目的


希望这能澄清问题。

因此优先级首先是比较器,然后是对象。但是默认情况下,AFAIK对象总是获得第一优先级。这里没有优先级
Intersect
方法使用用户提供的比较器,或者在用户未提供比较器时使用
DefaultEqualityComparer
DefaultEwualityComparer
调用对象上的
GetHashCode
返回cus1.GetHashCode()==cus2.GetHashCode()