是否为区域对象的类重载了==和/或!=运算符?
现在您已经发布了重载代码:
重载应该如下所示(代码取自Jon Skeet和Philip Rieck的帖子):
public static bool operator ==(Region r1, Region r2) { if (object.ReferenceEquals( r1, r2)) { // handles if both are null as well as object identity return true; } if ((object)r1 == null || (object)r2 == null) { return false; } return (r1.Cmr.CompareTo(r2.Cmr) == 0 && r1.Id == r2.Id); } public static bool operator !=(Region r1, Region r2) { return !(r1 == r2); }
那些操作员过载被打破了.
首先,如果通过调用==并反转结果来实现!=,它会使生活变得更加容易.
其次,在无效检查之前==应该有:
if (object.ReferenceEquals(r1, r2)) { return true; }
两个重载都不正确
public static bool operator ==(Region r1, Region r2) { if (object.ReferenceEquals(r1, null)) { return false; } if (object.ReferenceEquals(r2, null)) { return false; } return (r1.Cmr.CompareTo(r2.Cmr) == 0 && r1.Id == r2.Id); }
如果r1和r2为null,则第一个测试(object.ReferenceEquals(r1,null))将返回false,即使r2也为null.
尝试
//ifs expanded a bit for readability public static bool operator ==(Region r1, Region r2) { if( (object)r1 == null && (object)r2 == null) { return true; } if( (object)r1 == null || (object)r2 == null) { return false; } //btw - a quick shortcut here is also object.ReferenceEquals(r1, r2) return (r1.Cmr.CompareTo(r2.Cmr) == 0 && r1.Id == r2.Id); }