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

后端 未结 7 1271
故里飘歌
故里飘歌 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 05:48

    Yes. == checks for reference equality. Use Equals where you want to compare content.

    You might be wondering why this is so with objects. When you set an integer (value type) to an object variable, an operation called boxing happens. This operation wraps the value type into an object and puts it on the heap and returns a reference. This happens twice and references becomes different (although the values are the same).

提交回复
热议问题