为什么在包含期间不调用 GetHashCode?

Why is GetHashCode not called during Contains?

直到今天我的理解是 HashSetContains 中使用 GetHashCode。这也被称为例如here.

我写了一点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。相反,它 returns true.

为什么?

如果您使用 HashSet.Contains 将您的自定义比较器传递给 the constructor

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

现在 GetHashCode is used since you use a set based collection and not Enumerable.Contains 只是枚举所有项目并将它们与 Equals.

进行比较