Surprising Tuple (in)equality(令人惊讶的元组(不)等式)
问题描述
直到今天,我对 .NET Tuple
类的理解是它们将 Equals()
的实现委托给它们的内容,让我可以对它们进行等同和比较按价值".
Until today, my understanding of .NET Tuple
classes had been that they delegate their implementation of Equals()
to their contents, allowing me to equate and compare them "by value".
然后这个测试出现了,把我弄傻了:
Then this test came along and made a fool out of me:
[TestMethod]
public void EquateTwoTuplesWithSameContent()
{
var t1 = Tuple.Create("S");
var t2 = Tuple.Create((object)t1.Item1);
Assert.IsTrue(t1.Equals(t2)); // Boom!
}
阅读 MSDN 文档和各种博客给我留下了更多问题.从我的收集来看,似乎 Tuple
和 Tuple
总是被认为是不相等的,不管这两个实例可能包装同一个对象的事实(盒装或类型转换 - 都是一样的).
Reading through MSDN documentation and various blogs has left me with more questions. From what I gather, it would seem that Tuple<object>
and Tuple<TWhatever>
are always considered not equal, regardless of the fact that both instances may wrap the same object (boxed or typecast - it's all the same).
这真的是 Tuples
应该如何表现的吗?结构兼容性实际上是对平等的附加约束,而不是放松,正如我一直在解释它吗?
Is this really how Tuples
are supposed to behave? Is structural compatibility actually an additional constraint on equality as opposed to a relaxation, as I've been interpreting it until now?
如果是这样,我可以使用 BCL 中的其他内容来满足上述单元测试的期望吗?
If so, is there anything else in the BCL that I can use to meet the expectations of the above unit test?
提前谢谢你!
推荐答案
元组需要满足以下条件才能将对象视为相等":
Tuples require the following to be true for the objects to be considered "equal":
- 必须是具有与当前对象相同数量的泛型参数的 Tuple 对象.
- 这些泛型参数中的每一个都必须与另一个的类型相同.
- 元组的每个成员必须与另一个对应成员具有相同的值.
因此,因为 Tuple
具有与 Tuple
不同的通用参数,所以即使对象实际上是对与强类型 Tuple
具有相同值的字符串.
So, because a Tuple<object>
has a different generic parameter than a Tuple<string>
, they are not equal even if the object is actually a reference to a string of the same value as the strongly-typed Tuple<string>
.
这篇关于令人惊讶的元组(不)等式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:令人惊讶的元组(不)等式
基础教程推荐
- c# Math.Sqrt 实现 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- 将 XML 转换为通用列表 2022-01-01
- 如何激活MC67中的红灯 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- MS Visual Studio .NET 的替代品 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01
- rabbitmq 的 REST API 2022-01-01