【问题标题】:C#: best practice to overload == operator when it comes to null referencesC#:在涉及空引用时重载 == 运算符的最佳实践
【发布时间】:2010-11-02 16:16:31
【问题描述】:

在进行空引用比较时,重载比较同一类的两个实例的 == 运算符的最佳做法是什么?

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;

  ... 
}

比较处理空引用的最佳方法是什么?

【问题讨论】:

    标签: c# .net


    【解决方案1】:

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

    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);
    
    }
    

    【讨论】:

    • object.ReferenceEquals(o2, null)) 检查不是绝对必要的。赔率是Equals 做的第一件事就是做同样的检查。
    【解决方案2】:

    【讨论】:

      【解决方案3】:
      if (ReferenceEquals(o1, null) && ReferenceEquals(o2, null))
          return true;
      

      【讨论】:

        猜你喜欢
        • 2015-07-02
        • 2023-03-07
        • 1970-01-01
        • 1970-01-01
        • 2011-03-14
        • 2011-01-10
        • 2011-01-19
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多