直到今天我的理解是
HashSet
在 GetHashCode
中使用 Contains
。这也是说的,例如这里。
我写了一点
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
中使用自定义比较器,请将其传递给 构造函数。
var x = new HashSet<string>(new MyComparer());
x.Add("hello");
x.Add("world");
bool helloInside = x.Contains("hello");
现在使用
GetHashCode
,因为您使用基于集合的集合,而不是Enumerable.Contains
,它只是枚举所有项目并将它们与Equals
进行比较。