Definition of “==” operator for Double

前端 未结 5 613
萌比男神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:25

    The source of the primitive types can be confusing. Have you seen the very first line of the Double struct?

    Normally you cannot define a recursive struct like this:

    public struct Double : IComparable, IFormattable, IConvertible
            , IComparable, IEquatable
    {
        internal double m_value; // Self-recursion with endless loop?
        // ...
    }
    

    Primitive types have their native support in CIL as well. Normally they are not treated like object-oriented types. A double is just a 64-bit value if it is used as float64 in CIL. However, if it is handled as a usual .NET type, it contains an actual value and it contains methods like any other types.

    So what you see here is the same situation for operators. Normally if you use the double type type directly, it will never be called. BTW, its source looks like this in CIL:

    .method public hidebysig specialname static bool op_Equality(float64 left, float64 right) cil managed
    {
        .custom instance void System.Runtime.Versioning.NonVersionableAttribute::.ctor()
        .custom instance void __DynamicallyInvokableAttribute::.ctor()
        .maxstack 8
        L_0000: ldarg.0
        L_0001: ldarg.1
        L_0002: ceq
        L_0004: ret
    }
    

    As you can see, there is no endless loop (the ceq instrument is used instead of calling the System.Double::op_Equality). So when a double is treated like an object, the operator method will be called, which will eventually handle it as the float64 primitive type on the CIL level.

提交回复
热议问题