问题描述
尝试验证自己时,C#Equals for IEnumerables是一个引用equals,我发现了一些奇怪的东西。在NUnit中使用以下设置
While trying to verify to myself, that C# Equals for IEnumerables is a reference equals, I found something odd. With the following setup in NUnit
var a = (IEnumerable<string>)(new[] { "one", "two" });
var b = (IEnumerable<string>)(new[] { "one", "two" });
此测试
Assert.IsFalse(a.Equals(b));
通过此测试
Assert.AreNotEqual(a, b);
任何人都可以解释为什么?
doesn't. Can anybody explain why?
编辑:感谢您的答案。我只是读了NUnit的文档,它说同样的事情,AreEqual和AreNotEqual与集合测试集合的每个元素的相等。我想我被困在这个概念,AreEqual和AreNotEqual只是使用纯平等。
Thanks for the answers. I just read the documentation for NUnit, and it says the same thing, that AreEqual and AreNotEqual with collections test for equality of each element of the collection. I guess I was stuck with the notion, that AreEqual and AreNotEqual was just using plain Equals.
推荐答案
调用 a.Equals(b)
返回 false
,因为a和b不是同一个对象(尽管它们当然是相同的枚举)。 Equals
方法,除非被覆盖,否则会通过引用自动比较对象,这是在这种情况下发生的。
The call to a.Equals(b)
returns false
because a and b are not the same objects (though they are of course identical enumerations). The Equals
method, unless overridden, automatically compares objects by their reference, which is what is happening in this case.
有点比这更聪明。它是为调试目的而设计的,与 Equals
方法不同,因此它实际上比较两个枚举产生的序列,因为它识别 IEnumerable< T> ;
作为特殊类型。你应该也注意到它做了其他有趣的事情,例如当两个参数在数字上相同但是不同的值类型时返回 true
(例如 short
和 long
)。
Assert.AreNotEqual
is a bit more clever than this. It is designed for debugging purposes, unlike the Equals
method, so it in fact compares the sequences yielded by the two enumerations, since it recognises IEnumerable<T>
as a special type. You should also notice that it does other interesting things, such as returning true
when the two parameters are numerically identical but of different value types (e.g. short
and long
).
希望有帮助。
这篇关于C#Assert.AreNotEqual vs. Equals的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!