【问题标题】:In the msdn guidance on Equals override, why the cast to object in the null check?在有关等于覆盖的 msdn 指南中,为什么在 null 检查中强制转换为对象?
【发布时间】:2009-11-01 20:48:37
【问题描述】:

我只是在看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);
}

【问题讨论】:

    标签: c# operator-overloading


    【解决方案1】:

    == 操作符可能会被覆盖,如果被覆盖,默认的引用比较可能不是你得到的。强制转换为 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】:

      我更喜欢在这种模棱两可的上下文中使用object.ReferenceEquals(a, b) 来强制进行引用比较,因为它在保持语义精确的同时明确意图(事实上,ReferenceEquals 就是这样实现的)。 p>

      【讨论】:

        【解决方案3】:

        我想,由于这篇文章还谈到了覆盖运算符==,所以它迫使它使用在 Object 上定义的 == 运算符,而不是当前类中的任何重载运算符。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2016-02-02
          • 1970-01-01
          • 1970-01-01
          • 2012-11-05
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多