Definition of “==” operator for Double

前端 未结 5 600
萌比男神i
萌比男神i 2020-12-23 08:38

For some reason I was sneaking into the .NET Framework source for the class Double and found out that the declaration of == is:

public static bo         


        
5条回答
  •  离开以前
    2020-12-23 09:08

    I took a look at the CIL with JustDecompile. The inner == gets translated to the CIL ceq op code. In other words, it's primitive CLR equality.

    I was curious to see if the C# compiler would reference ceq or the == operator when comparing two double values. In the trivial example I came up with (below), it used ceq.

    This program:

    void Main()
    {
        double x = 1;
        double y = 2;
    
        if (x == y)
            Console.WriteLine("Something bad happened!");
        else
            Console.WriteLine("All is right with the world");
    }
    

    generates the following CIL (note the statement with label IL_0017):

    IL_0000:  nop
    IL_0001:  ldc.r8      00 00 00 00 00 00 F0 3F
    IL_000A:  stloc.0     // x
    IL_000B:  ldc.r8      00 00 00 00 00 00 00 40
    IL_0014:  stloc.1     // y
    IL_0015:  ldloc.0     // x
    IL_0016:  ldloc.1     // y
    IL_0017:  ceq
    IL_0019:  stloc.2
    IL_001A:  ldloc.2
    IL_001B:  brfalse.s   IL_002A
    IL_001D:  ldstr       "Something bad happened!"
    IL_0022:  call        System.Console.WriteLine
    IL_0027:  nop
    IL_0028:  br.s        IL_0035
    IL_002A:  ldstr       "All is right with the world"
    IL_002F:  call        System.Console.WriteLine
    IL_0034:  nop
    IL_0035:  ret
    

提交回复
热议问题