Two .NET objects that are equal don't say they are

后端 未结 7 1237
故里飘歌
故里飘歌 2020-12-06 05:09

I have the following code:

object val1 = 1;
object val2 = 1;

bool result1 = (val1 == val2);//Equals false
bool result2 = val1.Equals(val2); //Equals true
         


        
7条回答
  •  春和景丽
    2020-12-06 05:56

    The CIL for your code boxes the two integers and compares the two objects that result from the boxing (==). This comparison is by reference.

      .locals init ([0] object val1,
               [1] object val2,
               [2] bool result1,
               [3] bool result2)
      IL_0000:  nop
      IL_0001:  ldc.i4.1
      IL_0002:  box        [mscorlib]System.Int32
      IL_0007:  stloc.0
      IL_0008:  ldc.i4.1
      IL_0009:  box        [mscorlib]System.Int32
      IL_000e:  stloc.1
      IL_000f:  ldloc.0
      IL_0010:  ldloc.1
      IL_0011:  ceq
      IL_0013:  stloc.2
      IL_0014:  ldloc.0
      IL_0015:  ldloc.1
      IL_0016:  callvirt   instance bool [mscorlib]System.Object::Equals(object)
      IL_001b:  stloc.3
    

    For the .Equals it calls Object.Equals, which calls Int32.Equals (virtual method call on Object):

    public override bool Equals(object obj)
    {
        return ((obj is int) && (this == ((int) obj)));
    }
    

    This casts to int and compares the values as integers, a value type comparison.

提交回复
热议问题