在涉及空引用比较时,重载==运算符的最佳实践是什么,它比较同一类的两个实例?
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)
| 归档时间: |
|
| 查看次数: |
1043 次 |
| 最近记录: |