为什么在 Contains 期间不调用 GetHashCode?
直到今天,我的理解是 HashSet
在 Contains
中使用 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您想在
HashSet.Contains
中使用自定义比较器,请将其传递给 构造函数。现在使用
GetHashCode
因为您使用基于集合的集合而不是Enumerable.Contains
它只是枚举所有项目并将它们与Equals
进行比较。If you want to use your custom comparer in
HashSet.Contains
, pass it to the the constructor.Now
GetHashCode
is used since you use a set based collection and notEnumerable.Contains
which just enumerates all items and compares them withEquals
.