假设我定义了两个元组:

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

如果我尝试比较元组,则会得到不同的结果
bool result1 = (tuple1 == tuple2);    // FALSE
bool result2 = tuple1.Equals(tuple2); // TRUE

我希望两个调用都返回true。 ==到底在比较什么?

最佳答案

对于Tuple,==正在比较对象引用,因为它不会重载==运算符。由于对象是等效的,但不是相同的特定实例,因此Equals()返回true,而==返回false

许多类型不会重载==,有些则倾向于区分Equals()==的等效性。

另外,依靠==进行等效处理可能会导致一些怪异现象:

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

上面的代码将始终检查引用是否相等,因为在编译时将不受约束的泛型视为object,因此,如果该方法不是虚拟的,则将获取对象的版本(即使类型,例如string重载==)。

因此上述代码的用法:
var x = "Hello";
var y = "H";

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

是的,字符串是等效的,是的Tstring,但是由于泛型不受约束,因此==绑定(bind)到对象的==,因此即使具有显式false参数的相同代码将返回string,也将返回true

关于c# - 元组==困惑,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/9826664/

10-11 23:04
查看更多