ToLookup IEqualityComparer 参数始终为空
本文关键字:IEqualityComparer 参数 ToLookup | 更新日期: 2024-11-08 19:22:53
我偶然遇到了一个奇怪的问题,这对我来说并没有意义。
我有一个业务对象地址,其中包含属性位置(类型为 SqlGeography)。出于我的要求,我必须对位置进行查找,因为每个确切位置可能有多个地址。
由于 SqlGeography 是一种复杂的类型,我怀疑查找可能不起作用,因为它由于某种原因不基于位置坐标,所以我这样做了:
public class Address
{
public Address(byte[] location)
{
Location = SqlGeography.Deserialize(new SqlBytes(location));
}
public SqlGeography Location { get; set; }
}
public class SqlGeographyComparer : IEqualityComparer<SqlGeography>
{
public bool Equals(SqlGeography x, SqlGeography y)
{
// !!! always entered but for some reason x + y always null
if (x == null && y == null)
return true;
if (x == null ^ y == null)
return false;
return x.STEquals(y).IsTrue;
}
public int GetHashCode(SqlGeography obj)
{
return obj.GetHashCode();
}
}
class Program
{
static void Main(string[] args)
{
var addresses = GetAddresses();
// should be 2 but it's 3 results
var addressesLookup = addresses.ToLookup(d => d.Location);
// should be 2 but it's 3 results
var addressesLookup2 = addresses.ToLookup(d => d.Location, new SqlGeographyComparer());
Console.ReadLine();
}
private static IList<Address> GetAddresses()
{
// 230,16,0,0,1,12,213,97,212,23,126,78,72,64,109,51,198,37,82,163,32,64
var result = new List<Address>();
result.Add(new Address(new byte[] { 230, 16, 0, 0, 1, 12, 213, 97, 212, 23, 126, 78, 72, 64, 109, 51, 198, 37, 82, 163, 32, 64 }));
result.Add(new Address(new byte[] { 230, 16, 0, 0, 1, 12, 213, 97, 212, 23, 126, 78, 72, 64, 109, 51, 198, 37, 82, 163, 32, 64 }));
result.Add(new Address(new byte[] { 230, 16, 0, 0, 1, 12, 213, 97, 212, 23, 126, 78, 72, 64, 109, 51, 198, 37, 82, 163, 32, 63 }));
return result;
}
}
这是我没有听说过的关于 ToLookup 只是不将对象传递到给定比较器实例中的一些奇怪错误吗?!
有一次我更改了 SqlGeographyComparer 以覆盖其方法,如下所示:
public int GetHashCode(SqlGeography obj)
{
unchecked
{
return ((obj.Lat.GetHashCode() * 397) ^ obj.Long.GetHashCode());
}
}
它工作正常。
事实证明,GetHashCode必须模仿所需的相等比较(如Equals中所写),以使参数正常工作。
实现 GetHashCode 的参考,以防其他人偶然发现这个问题并想知道 397:
被覆盖的System.Object.GetHashCode的最佳算法是什么?