【发布时间】: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;
}
}
【问题讨论】:
-
afaik,这两个是可散列的,即使成员相同,散列也会不同
标签: c# iequalitycomparer