c# NaN comparison differences between Equals() and ==

后端 未结 4 407
失恋的感觉
失恋的感觉 2020-12-10 02:41

Check this out :

    var a = Double.NaN;

    Console.WriteLine(a == a);
    Console.ReadKey();

Prints \"False\"

    var a          


        
4条回答
  •  执笔经年
    2020-12-10 03:05

    If I were to venture a guess, it might be that this is to support the use of double values as keys in a dictionary.

    If x.Equals(y) returned false for x = double.NaN and y = double.NaN, then you could have code like this:

    var dict = new Dictionary();
    
    double x = double.NaN;
    
    dict.Add(x, "These");
    dict.Add(x, "have");
    dict.Add(x, "duplicate");
    dict.Add(x, "keys!");
    

    I think the majority of developers would find this behavior rather unintuitive. But even more counterintuitive would be this:

    // This would output false!
    Console.WriteLine(dict.ContainsKey(x));
    

    Basically, with an implementation of Equals that never returns true for a certain value, what you would have is a type capable of providing keys with the following bizarre behavior:

    • Could be added an unlimited number of times to a dictionary
    • Could not be detected using ContainsKey, and therefore...
    • Could never be removed using Remove

    Remember that Equals is very closely related to GetHashCode for this very reason (the C# compiler even warns you if you've overridden one without the other)—a big part of why they're there in the first place is to facilitate the use of types as hash table keys.

    Like I said, it's just a guess.

提交回复
热议问题