直到今天我的理解是 HashSet
在 Contains
中使用 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/