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

在空签入重写等于[duplicate]之前强制转换为对象

  •  9
  • fearofawhackplanet  · 技术社区  · 15 年前

    here

    下面的片段让我困惑。。。

    // If parameter cannot be cast to Point return false.
    TwoDPoint p = obj as TwoDPoint;
    if ((System.Object)p == null) // <-- wtf?
    {
        return false;
    }
    

    为什么有演员 Object 在这里表演 null

    6 回复  |  直到 15 年前
        1
  •  9
  •   Marc Gravell    15 年前

    运算符通过静态分析(和重载)应用,而不是通过虚拟方法(重写)应用。对于cast,它正在执行引用相等性检查。如果没有演员,它可以运行 TwoDPoint

    不过,就我个人而言,我会用 ReferenceEquals

        2
  •  3
  •   Paul Michalik    15 年前

    不!如果不这样做,运行时将开始递归调用您所使用的相等运算符,这将导致无限递归,从而导致堆栈溢出。

        3
  •  0
  •   Richard Friend    15 年前

    强制它使用对象的Equals方法而不是它自己的重载版本。。。只是一个猜测。。。

        4
  •  0
  •   Paolo Tedesco    15 年前

        5
  •  0
  •   Massimiliano Peluso    15 年前

    下面是演员的台词

    TwoDPoint p = obj as TwoDPoint
    

    与“normal”类型转换的区别在于,如果对象不是“castable”,则使用“As”不会引发异常。在这种情况下,如果“p”不是 TwoDPoint

    if ((System.Object)p == null) // <-- wtf? 
    { 
        return false; 
    } 
    

    出于上述原因,此代码检查强制转换是否正常如果不正常,则p应为空

        6
  •  0
  •   Jeff Ogata    15 年前

    请注意,这是VS2005文档。我想那些编写文档的人也有同样的问题,无法给出一个好的答案;VS 2008的例子已经改变了。这是 current version :

    public bool Equals(TwoDPoint p)
    {
        // If parameter is null, return false.
        if (Object.ReferenceEquals(p, null))
        {
            return false;
        }
    
        // Optimization for a common success case.
        if (Object.ReferenceEquals(this, p))
        {
            return true;
        }
    
        // If run-time types are not exactly the same, return false.
        if (this.GetType() != p.GetType())
            return false;
    
        // Return true if the fields match.
        // Note that the base class is not invoked because it is
        // System.Object, which defines Equals as reference equality.
        return (X == p.X) && (Y == p.Y);
    }