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

标签 c# hashset hashcode

直到今天我的理解是 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。相反,它返回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因为您使用基于集合的集合而不是 Enumerable.Contains它只是枚举所有项目并将它们与 Equals 进行比较。

关于c# - 为什么在 Contains 期间不调用 GetHashCode?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71351003/

相关文章:

c# - 如何在 C# 中替换 CSS 文件中的值?

c# - 在数据库中存储/检索 JSON 字符串,使其易于在代码中使用

java - Scala 中可变 HashSet 类的更新方法

c# - 我读到过遍历 HashSet 是不好的做法。我应该先调用 .ToList() 吗?

Java:通知提供者的实现与 hashCode 驱动的 Map

java - 当使用具有 Hibernate 多对多关系的 Set 时,是否需要重写 hashCode?

c# - 1 个资源文件与多个

java - 并发访问对 HashSet 的影响

java - 使用 List 对象覆盖 POJO 上的 equals 和 hashCode

c# - Visual Studio 2019 中的构建错误在错误列表中的显示不一致