注意:我的情况是针对 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
在你的类(class):
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);
}
}
您可能还想实现 IEqualityComparer<T>
和GetHashCode()
在你的ByteArrayComparer
类(class)。 EqualityComparer<T>.Default
返回实现此接口(interface)的类的实例,但我假设您不想使用这个实例,因为您已经实现了自己的自定义比较器。
关于c# - 如何使用 EqualityComparer<T>.Default 的自定义比较器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55361430/