Object equality behaves different in .NET

前端 未结 9 2092
旧巷少年郎
旧巷少年郎 2020-12-07 01:58

I have these statements and their\' results are near them.

string a = \"abc\";
string b = \"abc\";

Console.Writeline(a == b); //true

object x = a;
object y         


        
9条回答
  •  余生分开走
    2020-12-07 02:45

    When you say string1 == string2, the comparison uses the string type's overloaded == operator, which compares the strings' values.

    When you say object1 == object2, even though they're strings in this case, they won't qualify as strings for the purposes of finding an operator. So the comparison uses the default == operator, which compares the references for equality. Which means, if the two objects aren't the exact same object, it will return false.

提交回复
热议问题