.NET:double.Equals的奇怪的行为()拳击时, [英] .NET: Strange behaviour of double.Equals() when boxing
问题描述
这是怎么回事吗?
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 double
s. 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屋!