C# object is not null but (myObject != null) still return false

后端 未结 8 1938
不知归路
不知归路 2020-12-05 10:57

I need to do a comparaison between an object and NULL. When the object is not NULL I fill it with some data.

Here is the code :

 if (region != null)
         


        
8条回答
  •  独厮守ぢ
    2020-12-05 11:29

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

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

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

提交回复
热议问题