为什么在 Contains 期间不调用 GetHashCode?

发布于 2025-01-11 19:07:51 字数 807 浏览 3 评论 0原文

直到今天,我的理解是 HashSetContains 中使用 GetHashCode。例如这里也这么说。

我写了一些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

为什么?

Until today my understanding was that a HashSet uses GetHashCode inside Contains. That is also said e.g. here.

I wrote a little IEqualityComparer:

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

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

And used it like so:

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

But TestMyComparer does not throw a NotImplementedException, as I expected. Instead, it returns true.

Why?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

亣腦蒛氧 2025-01-18 19:07:51

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

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

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

If you want to use your custom comparer in HashSet.Contains, pass it to the the constructor.

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

Now GetHashCode is used since you use a set based collection and not Enumerable.Contains which just enumerates all items and compares them with Equals.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文