Two .NET objects that are equal don't say they are

后端 未结 7 1244
故里飘歌
故里飘歌 2020-12-06 05:09

I have the following code:

object val1 = 1;
object val2 = 1;

bool result1 = (val1 == val2);//Equals false
bool result2 = val1.Equals(val2); //Equals true
         


        
7条回答
  •  隐瞒了意图╮
    2020-12-06 06:07

    If you aren't using object but a custom class, you can override the == and != operators, and should probably implement the IEqualityComparer interface

    public static bool operator ==(MyType left, MyType right)
    {
        //code here, don't forget about NULLS when writing comparison code!!!
    }
    
    public static bool operator !=(MyType left, MyType right)
    {
        return !(left == right);
    }
    
    public bool Equals(MyType x, MyType y)
    {
        return (x == y);
    }
    
    public int GetHashCode(MyType obj)
    {
        return base.GetHashCode();
    }
    

提交回复
热议问题