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

后端 未结 8 1935
不知归路
不知归路 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:45

    Both of the overloads are incorrect

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

    if r1 And r2 are null, the first test (object.ReferenceEquals(r1, null)) will return false, even though r2 is also null.

    try

    //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);
        }
    
    0 讨论(0)
  • 2020-12-05 11:49

    This can sometimes happen when you have multiple threads working with the same data. If this is the case, you can use a lock to prevent them from messing with eachother.

    0 讨论(0)
提交回复
热议问题