Tuple == Confusion

情到浓时终转凉″ 提交于 2019-12-06 17:11:04

问题


Suppose I define two tuples:

Tuple<float, float, float, float> tuple1 = new Tuple<float, float, float, float>(1.0f, 2.0f, 3.0f, 4.0f);
Tuple<float, float, float, float> tuple2 = new Tuple<float, float, float, float>(1.0f, 2.0f, 3.0f, 4.0f);

If I try to compare the tuples, I get different results

bool result1 = (tuple1 == tuple2);    // FALSE
bool result2 = tuple1.Equals(tuple2); // TRUE

I would expect for both calls to return true. What exactly is == comparing?


回答1:


For Tuple, the == is comparing the object references because it does not overload the == operator. Since the objects are equivalent, but not the same specific instance, Equals() returns true and == returns false.

Many types do not overload ==, some prefer to keep a distinction between Equals() for equivalence and == for reference equality.

In addition, relying on == for equivalence can lead to some weirdness:

public bool AreSame<T>(T first, T second) where T : class
{
    return first == second;
}

The code above will always check for reference equality because an unconstrained generic is considered an object at compile time, thus if the method isn't virtual, you will get object's version (even if the type, such as string overloads ==).

Thus this usage of the above code:

var x = "Hello";
var y = "H";

// doing concat to avoid string interring
AreSame(x, y+"ello");

Yes, the strings are equivalent, yes T is string, but the == is bound to object's == since the generic is unconstrained, thus this will return false even though the same code with explicit string parameters would return true.




回答2:


== is comparing object references. The Tuple class does not overload the == operator, so you need to use .Equals.




回答3:


== for Tuple will only see the references and hence you will see that it is false.

PS: Recommended way is to do something like:

var tuple1 = Tuple.Create(1.0f, 2.0f, 3.0f, 4.0f)


来源:https://stackoverflow.com/questions/9826664/tuple-confusion

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!