为什么 EqualityComparer.Default 无法比较字典?
Why does EqualityComparer.Default fail to compare dictionaries?
为什么这个简单的测试会失败?
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;
}
}
如documentation中所述:
The Default property checks whether type T
implements the System.IEquatable<T>
interface and, if so, returns an EqualityComparer<T>
that uses that implementation. Otherwise, it returns an EqualityComparer<T>
that uses the overrides of Object.Equals
and Object.GetHashCode
provided by T
.
由于 IDictionary<TKey,TValue>
没有实现 System.IEquatable<IDictionary<TKey,TValue>>
,将返回一个相等比较器,它使用 T
提供的 Object.Equals
和 Object.GetHashCode
的覆盖。由于在您的情况下这两种方法都没有被覆盖,因此将返回默认实现,结果有两个字典,即使所有键都相同并且所有对应的值都相同,包含它们的字典不相等。
为什么这个简单的测试会失败?
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;
}
}
如documentation中所述:
The Default property checks whether type
T
implements theSystem.IEquatable<T>
interface and, if so, returns anEqualityComparer<T>
that uses that implementation. Otherwise, it returns anEqualityComparer<T>
that uses the overrides ofObject.Equals
andObject.GetHashCode
provided byT
.
由于 IDictionary<TKey,TValue>
没有实现 System.IEquatable<IDictionary<TKey,TValue>>
,将返回一个相等比较器,它使用 T
提供的 Object.Equals
和 Object.GetHashCode
的覆盖。由于在您的情况下这两种方法都没有被覆盖,因此将返回默认实现,结果有两个字典,即使所有键都相同并且所有对应的值都相同,包含它们的字典不相等。