繁体   English   中英

EValueComparer for KeyValuePair的问题

[英]issue with EqualityComparer for KeyValuePair

我有一个KeyValuePair类,实现IEquatable之后无法按预期工作。 我的单元测试失败了。 我想知道为什么测试失败?

类:

public class MyClass : IEquatable<MyClass>
{
    public KeyValuePair<int[], string> KeyValuePair { get; set; }

    public override bool Equals(object obj)
    {
        return Equals(obj as MyClass);
    }

    public bool Equals(MyClass other)
    {
        return other != null &&
               EqualityComparer<KeyValuePair<int[], string>>.Default.Equals(KeyValuePair, other.KeyValuePair);
    }

    public override int GetHashCode()
    {
        var hash = new HashCode();
        hash.Add(KeyValuePair);
        return hash.ToHashCode();
    }
}

测试:

[Fact]
    public void Test1()
    {
        MyClass expectedObject = new MyClass()
        {
            KeyValuePair = new KeyValuePair<int[], string>(new int[] { 1 }, "abc")
        };
        MyClass actualObject = new MyClass()
        {
            KeyValuePair = new KeyValuePair<int[], string>(new int[] { 1 }, "abc")
        };
        Assert.Equal(expectedObject, actualObject);
    }

测试结果:

消息:Assert.Equal()失败

您对Equals()实现不够深入。 因为:

Console.WriteLine("Are two int[] arrays equal? => "+
     EqualityComparer<int[]>.Default.Equals(new int[] { 1 }, new int[] { 1 }));

Console.WriteLine("Do two int[] have the same hashcode? => " +
     (new int[] { 1 }.GetHashCode() == new int[] { 1 }.GetHashCode()));

两个int []数组相等吗? =>错误

两个int []是否具有相同的哈希码? =>错误

您还必须为int[]数组实现Equals()GetHashCode()逻辑,例如:

public class EquatableIntArray : IEquatable<EquatableIntArray>
{
    public int[] Items { get; set; }

    public EquatableIntArray(int[] Items)
    {
        this.Items = Items;
    }

    public override bool Equals(object obj)
    {
        return Equals(obj as EquatableIntArray);
    }

    public bool Equals(EquatableIntArray other)
    {
        if (other == null) return false;
        if (ReferenceEquals(this, other)) return true;
        return other.Items != null && (this.Items?.SequenceEqual(other.Items)??false);
    }

    private int? cachedHashCode;

    public override int GetHashCode()
    {
        if (cachedHashCode.HasValue) return cachedHashCode.Value;
        int hc = Items.Length;
        for (int i = 0; i < Items.Length; ++i)
        {
            hc = unchecked(hc * 314159 + Items[i]);
        }
        return (cachedHashCode = hc).Value;
    }
}

(从此处实现GetHashCode()之上)

Console.WriteLine("Are two EquatableIntArrays equal? => " +
     EqualityComparer<EquatableIntArray>.Default.Equals(
         new EquatableIntArray(new int[] { 1 })
       , new EquatableIntArray(new int[] { 1 })));

 Console.WriteLine("Do two EquatableIntArrays have the same hashcode? => " +
      (new EquatableIntArray(new int[] { 1 }).GetHashCode()
    == new EquatableIntArray(new int[] { 1 }).GetHashCode()));

两个EquatableIntArrays是否相等? =>正确

两个EquatableIntArray是否具有相同的哈希码? =>正确

然后,在您的课程中,您将获得以下内容:

public class MyClass2 : IEquatable<MyClass2>
{
    public KeyValuePair<EquatableIntArray, string> KeyValuePair { get; set; }

    public override bool Equals(object obj)
    {
        return Equals(obj as MyClass2);
    }

    public bool Equals(MyClass2 other)
    {
        return other != null &&
               EqualityComparer<KeyValuePair<EquatableIntArray, string>>.Default.Equals(KeyValuePair, other.KeyValuePair);
    }
    private int? cachedHashCode;
    public override int GetHashCode()
    {
        if (cachedHashCode.HasValue) return cachedHashCode.Value;
        cachedHashCode = CombineHashCodes(KeyValuePair.Key.GetHashCode(), KeyValuePair.Value.GetHashCode());
        return cachedHashCode.Value;
    }

    internal static int CombineHashCodes(int h1, int h2)
    {
        return (((h1 << 5) + h1) ^ h2);
    }
}

(我在.NET Framework 4.7上进行了测试,并且那里没有HashCode类,因此我从Tuple借用了GetHashCode()实现)

和:

MyClass2 expectedObject2 = new MyClass2()
{
  KeyValuePair = new KeyValuePair<EquatableIntArray, string>(new EquatableIntArray(new int[] { 1 }), "abc")
};
MyClass2 actualObject2 = new MyClass2()
{
   KeyValuePair = new KeyValuePair<EquatableIntArray, string>(new EquatableIntArray(new int[] { 1 }), "abc")
};

Console.WriteLine("Are two MyClass2 instances equal? => "+ expectedObject2.Equals(actualObject2));

两个MyClass2实例相等吗? =>正确

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM