.NET: Strange behaviour of double.Equals() when boxing

倖福魔咒の 提交于 2019-12-13 13:10:15

问题


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

回答1:


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!



来源:https://stackoverflow.com/questions/2780022/net-strange-behaviour-of-double-equals-when-boxing

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