代码之家  ›  专栏  ›  技术社区  ›  Andrew Florko

C 35;:当引用为空时重载==运算符的最佳实践

  •  5
  • Andrew Florko  · 技术社区  · 15 年前

    当涉及到空引用比较时,重载==运算符比较同一类的两个实例的最佳实践是什么?

    MyObject o1 = null;
    MyObject o2 = null;
    if (o1 == o2) ... 
    
    
    static bool operator == (MyClass o1, MyClass o2)
    {
      // ooops! this way leads toward recursion with stackoverflow as the result
      if (o1 == null && o2 == null) 
        return true;   
    
      // it works!
      if (Equals(o1, null) && Equals(o2, null))
        return true;
    
      ... 
    }
    

    3 回复  |  直到 15 年前
        1
  •  11
  •   Andrew Shepherd    15 年前

    我想知道是否有“最佳方法”。我是这样做的:

    static bool operator == (MyClass o1, MyClass o2)
    {
      if(object.ReferenceEquals(o1, o2)) // This handles if they're both null
          return true;                   // or if it's the same object
    
      if(object.ReferenceEquals(o1, null))
          return false;
    
      if(object.ReferenceEquals(o2, null)) // Is this necessary? See Gabe's comment
           return false;
    
      return o1.Equals(o2);
    
    }
    
        2
  •  2
  •   klm_    15 年前
        3
  •  1
  •   Itay Karo    15 年前
    if (ReferenceEquals(o1, null) && ReferenceEquals(o2, null))
        return true;