【问题标题】:Why does EqualityComparer.Default fail to compare dictionaries?为什么 EqualityComparer.Default 无法比较字典?
【发布时间】:2018-08-22 07:59:36
【问题描述】:

为什么这个简单的测试会失败?

 var dict1 = new Dictionary<int, int> {{1, 15}};
 var dict2 = new Dictionary<int, int> {{1, 15}};

 var equals = EqualityComparer<IDictionary<int, int>>.Default.Equals(dict1, dict2);

 Assert.IsTrue(equals);

...非常感谢。我最终得到了我自己的字典……这看起来像是一个人应该做的事情吗?

public class EquatableDictionary<TKey, TValue> : Dictionary<TKey, TValue>, IEquatable<EquatableDictionary<TKey, TValue>>
{
    public EquatableDictionary() { }

    protected EquatableDictionary(SerializationInfo info, StreamingContext context) : base(info, context)
    {
    }

    public bool Equals(EquatableDictionary<TKey, TValue> other)
    {
        if (other == null)
            return false;

        foreach (var kvp in this)
        {
            if (!other.TryGetValue(kvp.Key, out var otherValue))
                return false;

            if (!Equals(kvp.Value, otherValue))
                return false;
        }

        return true;
    }
}

【问题讨论】:

标签: c# iequalitycomparer


【解决方案1】:

正如documentation中提到的:

Default 属性检查类型T 是否实现System.IEquatable&lt;T&gt; 接口,如果是,则返回使用该实现的EqualityComparer&lt;T&gt;。否则,它返回一个EqualityComparer&lt;T&gt;,它使用T 提供的Object.EqualsObject.GetHashCode 的覆盖。

由于IDictionary&lt;TKey,TValue&gt; 没有实现System.IEquatable&lt;IDictionary&lt;TKey,TValue&gt;&gt;,将返回一个相等比较器,它使用T 提供的Object.EqualsObject.GetHashCode 的覆盖。由于在您的情况下这两种方法都没有被覆盖,因此将返回默认实现,即使所有键相同且所有相应值相同,也会返回两个字典,包含它们的字典不相等。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-09-13
    • 1970-01-01
    • 2011-06-21
    • 2012-02-09
    • 1970-01-01
    • 2012-02-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多