如何为EqualityComparer <t> .Default使用自定义比较器?

时间:2019-03-26 15:59:11

标签: 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继承并重写方法,还是其他?

1 个答案:

答案 0 :(得分:1)

创建并使用自定义比较器的实例,而不是在类中使用 data test(drop=i); num = 0; do i=1 to 10; if rpq_stage_date_(num||i) ne . then stage_date_(num||i) = rpq_stage_date_(num||i); if gps_stage_date_(num||i) ne . then stage_date_(num||i) = gps_stage_date_(num||i); if ldr_stage_date_(num||i) ne . then stage_date_(num||i) = ldr_stage_date_(num||i); end; do i = 10 to 14; if rpq_stage_date_(i) ne . then stage_date_(i) = rpq_stage_date_(i); end; if gps_stage_date_(i) ne . then stage_date_(i) = gps_stage_date_(i); end; if ldr_stage_date_(i) ne . then stage_date_(i) = ldr_stage_date_(i); end; RUN; PROC PRINT data=test; run;

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); } } 类中实现IEqualityComparer<T>GetHashCode()ByteArrayComparer返回实现此接口的类的实例,但我假设您已实现自己的自定义比较器,因此不希望使用该实例。

How to use the IEqualityComparer