比较Double.NaN与自身 [英] Comparing Double.NaN with itself
问题描述
我被困试图找出为什么这两个操作返回不同的值:
I am stuck trying to find out why these two operations return different values:
-
Double.NaN == Double.NaN
返回假
-
Double.NaN.Equals(Double.NaN)
返回真
Double.NaN == Double.NaN
returnsfalse
Double.NaN.Equals(Double.NaN)
returnstrue
我有回答的第一部分,但没有第二个,而不是为什么这两个比较返回不同的值
I have the answer to the first part but not the second and not to "why are these two comparisons returning different values"
推荐答案
该差异的原因很简单,如果不是很明显。
The reason for the difference is simple, if not obvious.
如果您使用等于运算符 ==
,那么你使用IEEE测试是否相等。
If you use the equality operator ==
, then you're using the IEEE test for equality.
如果您使用的是等于(对象)
方法,那么你必须要保持的Object.Equals(对象)的合约
。当你实现这个方法(和相应的 GetHash code
方法),您必须维护合同,这是从IEEE的行为不同。
If you're using the Equals(object)
method, then you have to maintain the contract of object.Equals(object)
. When you implement this method (and the corresponding GetHashCode
method), you have to maintain that contract, which is different from the IEEE behaviour.
如果在等于
合同不成立,那么哈希表的行为都要碎了。
If the Equals
contract was not upheld, then the behaviour of hash tables would break.
var map = new Dictionary<double,string>();
map[double.NaN] = "NaN";
var s = map[double.NaN];
如果!double.NaN.Equals(double.NaN)
,你会不会把你的价值了字典!
If !double.NaN.Equals(double.NaN)
, you'd never get your value out of the dictionary!
如果在previous句话没有意义,那么明白,散列的机制(以使用字典&LT; T,U&GT;
, HashSet的&LT; T&GT;
等)同时使用的Object.Equals(对象)
和 object.GetHash code()
方法广泛,并且依靠自己的行为的保证。
If the previous sentence does not make sense, then understand that the mechanics of hashing (used in Dictionary<T,U>
, HashSet<T>
, etc) use both the object.Equals(object)
and object.GetHashCode()
methods extensively, and rely upon guarantees of their behaviour.
这篇关于比较Double.NaN与自身的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!