令人惊讶的元组(不)平等 [英] Surprising Tuple (in)equality

查看:127
本文介绍了令人惊讶的元组(不)平等的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

直到今天,我的.NET的理解元组类一直是他们委托其实施的等于() ,其内容,让我划上等号,并按值进行比较



那么这个测试走过来,并提出了傻瓜了我:

  [TestMethod的] 
公共无效EquateTwoTuplesWithSameContent()
{
VAR T1 = Tuple.Create(S) ;
变种T2 = Tuple.Create((对象)t1.Item1);
Assert.IsTrue(t1.Equals(T2)); //轰!
}



通过MSDN文档和各种博客读给我留下了更多的问题。从我收集,它似乎元组LT;对象> 元组LT; TWhatever> 总是被认为是不相等的,不管事实上,这两个实例可以换同一个对象(盒装或强制转换 - 这一切都一样)。



这真的是如何元组都应该表现?是结构性的兼容性实际上是一个的其他的平等,而不是放松约束,因为我一直在解释它到现在为止?



如果这样,还有什么BCL中,我可以用它来满足上述单元测试的期望?



感谢你在前进!


< DIV CLASS =h2_lin>解决方案

元组需要以下是真实的要考虑的对象,平等:




  • 必须是具有相同的号码作为当前对象的通用参数(多个)的一个元组对象。

  • 每个这些通用的参数必须是相同的类型的其他

  • 元组的每个成员都必须具有相同的值作为其他的相应部件。



所以,因为元组LT;对象> 已经超过了元组下不同的泛型参数;串> ,他们是不相等的,即使对象实际上是相同的值作为强类型元组℃的字符串的引用;串方式>


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!
}

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

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?

If so, is there anything else in the BCL that I can use to meet the expectations of the above unit test?

Thank you in advance!

解决方案

Tuples require the following to be true for the objects to be considered "equal":

  • Must be a Tuple object with the same number of generic parameter(s) as the current object.
  • Each of those generic parameters must be of the same type as the other.
  • Each member of the tuple must have the same value as the corresponding member of the other.

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

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

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