【发布时间】:2008-12-22 22:20:02
【问题描述】:
我今天在对通用字典进行单元测试时遇到了这个问题。
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 的意义何在?换句话说,为什么没有内置的方法来为泛型集合进行值相等?
编辑感谢您迄今为止的回复。显然我的例子是使用值类型,但我认为我的抱怨适用于所有对象。为什么泛型集合相等性不能只是其类型相等性的并集?意外的行为并没有真正削减它,因为有单独的规定来寻找参考平等。正如 Konrad Rudolph 指出的那样,我想这将引入集合的约束,即仅持有实现 IEquatable 的对象。但是,在 Dictionary 这样的对象中,这似乎并不过分。
【问题讨论】:
标签: c# generics collections comparison equality