Object equality behaves different in .NET

前端 未结 9 2067
旧巷少年郎
旧巷少年郎 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:42

    String has overloaded the equality operator so that you can use == for value comparison. Hence

    a == b //true.

    When you're downcasting them to object, you're only comparing references. String looks into an internal string-pool if another string instance is already available, otherwise a new instance will be created and added to the pool. So actually a, b, x and y are even the same reference, that's why

    x == y //true.

    With using the constructor of String, you're forcing .NET to create a new instance even if another string with the same value(length and character sequence) exists. That's why

    k == m //false

    http://en.csharp-online.net/CSharp_String_Theory%E2%80%94String_intern_pool

提交回复
热议问题