为什么在Contains期间没有调用GetHashCode?

问题描述 投票:0回答:1

直到今天我的理解是

HashSet
GetHashCode
中使用
Contains
。这也是说的,例如这里

我写了一点

IEqualityComparer
:

public class MyComparer : IEqualityComparer<string>
{
    public bool Equals(string? a, string? b)
    {
        return a == b;
    }

    public int GetHashCode(string a)
    {
        throw new NotImplementedException();
    }
}

并像这样使用它:

public void TestMyComparer()
{
    var x = new HashSet<string>(new []{ "hello", "world" });
    bool helloInside = x.Contains("hello", new MyComparer());
}

但是

TestMyComparer
并没有像我预期的那样抛出
NotImplementedException
。相反,它返回
true

为什么?

c# hashset hashcode
1个回答
3
投票

如果您想在

HashSet.Contains
中使用自定义比较器,请将其传递给 构造函数

var x = new HashSet<string>(new MyComparer());
x.Add("hello");
x.Add("world");
bool helloInside = x.Contains("hello");

现在使用

GetHashCode
,因为您使用基于集合的集合,而不是Enumerable.Contains
,它只是枚举所有项目并将它们与
Equals
进行比较。

© www.soinside.com 2019 - 2024. All rights reserved.