In the msdn guidance on Equals override, why the cast to object in the null check?

后端 未结 3 1230
南方客
南方客 2020-12-04 02:37

I was just looking at the Guidelines for Overloading Equals() on msdn (see code below); most of it is clear to me, but there is one line I don\'t get.

if ((S         


        
3条回答
  •  北海茫月
    2020-12-04 02:47

    The == operator may be overridden, and if it is, the default reference comparison may not be what you get. Casting to System.Object ensures that calling == performs a reference equality test.

    public static bool operator ==(MyObj a, MyObj b)
    {
      // don't do this!
      return true;
    }
    
    ...
    MyObj a = new MyObj();
    MyObj b = null;
    Console.WriteLine(a == b); // prints true
    Console.WriteLine((object)a == (object)b); // prints false
    

提交回复
热议问题