代码之家  ›  专栏  ›  技术社区  ›  Mathias

在关于Equals override的msdn指南中,为什么在null检查中强制转换为对象?

  •  4
  • Mathias  · 技术社区  · 16 年前

    我只是在看电视 Guidelines for Overloading Equals() on msdn (见下文代码);大部分对我来说都很清楚,但有一句话我不明白。

    if ((System.Object)p == null)
    

    if ((object)p == null)
    

    为什么不简单

     if (p == null)
    

    演员们反对买我们什么?

    public override bool Equals(System.Object obj)
    {
        // If parameter is null return false.
        if (obj == null)
        {
            return false;
        }
    
        // If parameter cannot be cast to Point return false.
        TwoDPoint p = obj as TwoDPoint;
        if ((System.Object)p == null)
        {
            return false;
        }
    
        // Return true if the fields match:
        return (x == p.x) && (y == p.y);
    }
    
    public bool Equals(TwoDPoint p)
    {
        // If parameter is null return false:
        if ((object)p == null)
        {
            return false;
        }
    
        // Return true if the fields match:
        return (x == p.x) && (y == p.y);
    }
    
    3 回复  |  直到 16 年前
        1
  •  11
  •   Michael Petrotta user3140870    16 年前

    这个 == 运算符可能被重写,如果是,则默认的引用比较可能不是您得到的结果。强制转换到System.Object可确保调用 执行引用相等性测试。

    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
    
        2
  •  3
  •   Konrad Rudolph    16 年前

    object.ReferenceEquals(a, b) 在这种模棱两可的上下文中,强制进行引用比较是因为它在保留语义的同时明确了意图 精确地 (事实上, ReferenceEquals

        3
  •  2
  •   tvanfosson    16 年前

    我认为,由于本文还讨论了重写运算符==,它迫使它使用在对象上定义的==运算符,而不是当前类中任何重载的运算符。