C#:当涉及空引用时,重载==运算符的最佳实践

时间:2010-11-02 07:46:08

标签: c# .net

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

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 个答案:

答案 0 :(得分:11)

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

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

}

答案 1 :(得分:2)

答案 2 :(得分:1)

if (ReferenceEquals(o1, null) && ReferenceEquals(o2, null))
    return true;