c# - 如何使用 EqualityComparer<T>.Default 的自定义比较器?

标签 c# iequalitycomparer

注意:我的情况是针对 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)的类的实例,但我假设您不想使用这个实例,因为您已经实现了自己的自定义比较器。

How to use the IEqualityComparer

关于c# - 如何使用 EqualityComparer<T>.Default 的自定义比较器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55361430/

相关文章:

c# - 将 IQueryable<T> 转换为 DbSet<T>

c# - "Attempted to read or write protected memory. This is often an indication that other memory is corrupt."来自 C# 的 Delphi7 DLL

c# - 如何在 C# 中使用 NI 库中的 VI

c# - 具有由 lambda 定义的自定义 IEqualityCompare 的 HashSet 构造函数?

c# - 如何使用 IEqualityComparer

c# - 进程交互(c#和纯c++)

c# - Unity截图错误: capturing the editor too

c# - 字典中类型的自定义相等比较器

c# - ICollection<>.Contains 在 EF 中,因为 HashSet 失败

c# - 具有整数键的哈希表(字典等)