直到今天我的理解是 aHashSet使用GetHashCodeinside 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.
為什么?
uj5u.com熱心網友回復:
如果您使用HashSet.Contains將自定義比較器傳遞給建構式。
var x = new HashSet<string>(new MyComparer());
x.Add("hello");
x.Add("world");
bool helloInside = x.Contains("hello");
使用NowGetHashCode 是因為您使用基于集合的集合,而不是Enumerable.Contains僅列舉所有專案并將它們與Equals.
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/437692.html
上一篇:“不是”模式和可為空的型別
下一篇:如何為ToolbarItem的IconImageSource使用Xamarin.Forms.Shapes.Path?
