[英]What comparer should I use for a .NET Dictionary to use the EqualityComparer<T> methods of the Key?
[英]How to use a custom comparer for EqualityComparer<T>.Default?
注意:我的情况是针对byte [],但我相信一个好的答案适用于任何类型。
Visual Studio的Equals
自动生成的实现使用EqualityComparer<T>.Default.Equals(T x, T y)
作为参考类型。 我有很多带有字节数组的类,它们需要包含在Equals
因此我想尽可能保留Visual Studio的代码,但是Default
返回字节数组的ObjectEqualityComparer
。 我已经编写了一个简单的字节数组比较器,但是我不确定如何继续使用它而不是ObjectEqualityComparer
。
public class Foo
{
public int Id {get;set;}
public byte[] Data {get;set;}
public override bool Equals(object obj)
{
var foo = obj as Foo;
return foo != null &&
Id == foo.Id &&
EqualityComparer<byte[]>.Default.Equals(Data, foo.Data);
}
}
static void Main
{
Foo f1 = new Foo { Id = 1, Data = new byte[1] { 0xFF } };
Foo f2 = new Foo { Id = 1, Data = new byte[1] { 0xFF } };
bool result = f1.Equals(f2); // false
}
public class ByteArrayComparer
{
public bool Equals(byte[] x, byte[] y)
{
return x.SequenceEqual(y);
}
public int GetHashCode(byte[] obj)
{
return obj.GetHashCode();
// as Servy said, this is wrong but it's not the point of the question,
// assume some working implementation
}
}
ByteArrayComparer应该实现IEqualityComparer,从EqualityComparer继承并重写方法,还是其他?
创建并使用自定义比较器的实例,而不是使用EqualityComparer<byte[]>.Default
类中的EqualityComparer<byte[]>.Default
:
public class Foo
{
public int Id { get; set; }
public byte[] Data { get; set; }
private readonly ByteArrayComparer _comparer = new ByteArrayComparer();
public override bool Equals(object obj)
{
var foo = obj as Foo;
return foo != null &&
Id == foo.Id &&
_comparer.Equals(Data, foo.Data);
}
}
您可能还想在ByteArrayComparer
类中实现IEqualityComparer<T>
和GetHashCode()
。 EqualityComparer<T>.Default
返回实现此接口的类的实例,但我假设您已实现自己的自定义比较器,因此不希望使用该实例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.