When is Double's == operator invoked?

前端 未结 3 1355
执笔经年
执笔经年 2021-02-18 14:22

It all started with a trick question that someone posed to me.. (It\'s mentioned in the book - C# in a nutshell) Here\'s the gist of it.

Double a = Double.NaN;
C         


        
3条回答
  •  南旧
    南旧 (楼主)
    2021-02-18 14:58

    In msdn it is stated that;

    If two Double.NaN values are tested for equality by calling the Equals method, the method returns true. However, if two NaN values are tested for equality by using the equality operator, the operator returns false. When you want to determine whether the value of a Double is not a number (NaN), an alternative is to call the IsNaN method.

    This is done delibaretly to conform with IEC 60559:1989 since it states that two NaN values are not equal as they are not treated as numbers, so op_Equal definition conforms with this standart;

    According to IEC 60559:1989, two floating point numbers with values of NaN are never equal.However, according to the specification for the System.Object::Equals method, it's desirable to override this method to provide value equality semantics. Since System.ValueType provides this functionality through the use of Reflection, the description for Object.Equals specifically says that value types should consider overriding the default ValueType implementation to gain a performance increase. In fact from looking at the source of System.ValueType::Equals (line 36 of clr\src\BCL\System\ValueType.cs in the SSCLI), there's even a comment from the CLR Perf team to the effect of System.ValueType::Equals not being fast.

    refer to: http://blogs.msdn.com/b/shawnfa/archive/2004/07/19/187792.aspx

提交回复
热议问题