.NET:double.Equals的奇怪的行为()拳击时, [英] .NET: Strange behaviour of double.Equals() when boxing

查看:122
本文介绍了.NET:double.Equals的奇怪的行为()拳击时,的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是怎么回事吗?

  INT零= 0;
双X = 0;
反对Y = X;

Console.WriteLine(x.Equals(零)); // 真正
Console.WriteLine(并且y.equals(零)); // 假
 

解决方案

在这里,你调用两种不同的方法 - Double.Equals(双)的Object.Equals(对象)。对于第一个呼叫, INT 隐式可转换为,这样的输入法是一种和它的两个秒之间的平等检查。然而,对于第二个电话时, INT 没有的被转换为,它只是被装箱。如果你看看在反射镜中的 Double.Equals(对象)的方法,第一行是:

 如果(!(obj是双))
{
    返回false;
}
 

所以它的返回false,因为输入的是盒装 INT ,不是盒装

好赶上!

What's going on here?

int zero = 0;
double x = 0;
object y = x;

Console.WriteLine(x.Equals(zero)); // True
Console.WriteLine(y.Equals(zero)); // False

解决方案

Here, you're calling two different methods - Double.Equals(double) and Object.Equals(object). For the first call, int is implicitly convertable to double, so the input to the method is a double and it does an equality check between the two doubles. However, for the second call, the int is not being cast to a double, it's only being boxed. If you have a look at the Double.Equals(object) method in reflector, the first line is:

if (!(obj is double))
{
    return false;
}

so it's returning false, as the input is a boxed int, not a boxed double.

Good catch!

这篇关于.NET:double.Equals的奇怪的行为()拳击时,的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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