我今天在对通用字典进行单元测试时遇到了这个问题。
System.Collections.Generic.Dictionary<int, string> actual, expected;
actual = new System.Collections.Generic.Dictionary<int, string> { { 1, "foo" }, { 2, "bar" } };
expected = new System.Collections.Generic.Dictionary<int, string> { { 1, "foo" }, { 2, "bar" } };
Assert.AreEqual(expected, actual); //returns false
失败,除非 actual == expected
(对象引用是相同的)。显然,actual.Equals(expected)
也返回 false。
很好,但是如果执行System.Collections.Generic.Dictionary<int, string>.Equals
只引用相等, IEquatable
有什么意义? ?换句话说,为什么没有内置的方法来实现通用集合的值相等?
编辑感谢您到目前为止的回复。显然我的例子是使用值类型,但我认为我的提示适用于所有对象。为什么泛型集合等式不能只是其类型的等式的并集?意外行为并不能真正解决问题,因为有单独的规定来查找引用相等性。我想这会引入仅持有实现 IEquatable
的对象的集合的约束正如康拉德·鲁道夫指出的那样。然而,在像 Dictionary 这样的对象中,这似乎并没有什么过分的要求。
最佳答案
In other words, why is there no baked-in way to do value equality for generic collections?
可能是因为很难用通用术语来表述,因为只有当字典的值类型(和键类型)也实现了 IEquatable
时,这才是可能的。 。然而,这样的要求太强烈了,使得 Dictionary
许多未实现此接口(interface)的类型无法使用。
这是受限泛型的固有问题。 Haskell 为这个问题提供了一个解决方案,但这需要更强大、更复杂的泛型机制。
请注意,IComparable
也有类似的情况。与容器相比,但有对此的支持,使用 Comparer<T>.Default
如果需要的话。
关于c# - System.Collections.Generic.Dictionary<T,T>.Equals 实际上做了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/387547/