gpt4 book ai didi

c# - 为什么 EqualityComparer.Default 无法比较字典?

转载 作者:太空宇宙 更新时间:2023-11-03 20:54:29 26 4
gpt4 key购买 nike

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

 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>> ,将返回一个使用 Object.Equals 覆盖的相等比较器和 Object.GetHashCodeT 提供.由于在您的情况下这两种方法都没有被覆盖,因此将返回默认实现,结果有两个字典,即使所有键都相同并且所有对应的值都相同,包含它们的字典不相等。

关于c# - 为什么 EqualityComparer.Default 无法比较字典?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51962285/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com