且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

C# 对象不为空,但 (myObject != null) 仍然返回 false

更新时间:2023-02-09 14:53:33

是否为区域对象的类重载了 == 和/或 != 运算符?

Is the == and/or != operator overloaded for the region object's class?

现在您已经发布了重载代码:

Now that you've posted the code for the overloads:

重载应该如下所示(代码取自 Jon SkeetPhilip Rieck):

The overloads should probably look like the following (code taken from postings made by Jon Skeet and 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);
}