[英]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.