什么检查 CollectionAssert.AreEquivalent [英] What check CollectionAssert.AreEquivalent

查看:25
本文介绍了什么检查 CollectionAssert.AreEquivalent的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读 一篇 MSDN 文章,根据 MSDN:

I was reading about the method CollectionAssert.AreEquivalent in a MSDN article and according to MSDN:

如果两个集合具有相同数量但顺序任意的相同元素,则它们是等价的.如果元素的值相等,则元素相等,而不是引用同一个对象.

Two collections are equivalent if they have the same elements in the same quantity, but in any order. Elements are equal if their values are equal, not if they refer to the same object.

我在 Visual Studio 中尝试了以下代码:

I tried the following code in Visual Studio:

var first = new TradeData { ID = "A", MarketPrice = 0 };
var mockFir = new TradeData { ID = "A", MarketPrice = 0 };
var collection = new List<TradeData> { first };
var mockCollection = new List<TradeData> { mockFir };
CollectionAssert.AreEquivalent(collection, mockCollection);

但我有一个例外:

CollectionAssert.AreEquivalent 失败

CollectionAssert.AreEquivalent failed

所以,我的问题是:当 MSDN 说如果元素的值相等,则元素相等,而不是引用同一个对象时,元素就相等"究竟是什么意思?

So, my question is: what exactly MSDN mean when they say that "Elements are equal if their values are equal, not if they refer to the same object"?

推荐答案

因为 TradeData 类没有覆盖 object.Equals,基础实现接管,比较两个对象的引用.尽管 firstmockFir 包含相同的值,但它们不是相同的对象,因此它们不被视为相等.如果您覆盖 TradeData 类中的 Equals,您的示例将起作用.

Because the TradeData class does not override object.Equals, the base implementation takes over, which compares two objects by reference. Although first and mockFir contain the same values they are not the same object and so they are not considered equal. If you override Equals in the TradeData class your example will work.

这篇关于什么检查 CollectionAssert.AreEquivalent的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆