令人惊讶的元组(不)等式

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 文档和各种博客给我留下了更多问题.从我的收集来看,似乎 TupleTuple 总是被认为是不相等的,不管这两个实例可能包装同一个对象的事实(盒装或类型转换 - 都是一样的).

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>.

这篇关于令人惊讶的元组(不)等式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:令人惊讶的元组(不)等式

基础教程推荐