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

And*_*rko 5 .net c#

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

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;

  ... 
}
Run Code Online (Sandbox Code Playgroud)

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

And*_*erd 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);

}
Run Code Online (Sandbox Code Playgroud)

  • `object.ReferenceEquals(o2,null))`检查不是绝对必要的.赔率是'Equals`做的第一件事就是做同样的检查. (4认同)