關於string的對象引用

來源:互聯網
上載者:User

什麼都不說了, 一切都在代碼裡:

 1             string a1 = "aaa";  // 在堆中分配"aaa"
 2              string a2 = "aaa";  // 堆中已有"aaa", 則不再給"aaa"分配新空間,a2指向a1的地址
 3             string a3 = new string("aaa".ToCharArray()); // new產生新的對象,分配新的空間
 4 
 5             Console.WriteLine(object.ReferenceEquals(a1, "aaa")); //Ture
 6             Console.WriteLine(object.ReferenceEquals(a1, a2));    //True
 7             Console.WriteLine(object.ReferenceEquals(a1, a3));    //False
 8 
 9             string b1 = "bbb";
10 
11             string c1 = "aaabbb";        // 定義"aaabbb"
12             string c2 = "aaa" + "bbb";   // "aaa"和"bbb"都是常量, 合成為"aaabbb"指向c1
13             string c3 = a1 + "bbb";      // a1是變數, 則給c3分配新的空間
14             string c4 = a1 + b1;         // 同上, c4分配新的空間
15             string c5 = a1 + b1;         // 同上, c5分配新的空間
16 
17             Console.WriteLine(object.ReferenceEquals(c1, c2));  //True
18             Console.WriteLine(object.ReferenceEquals(c1, c3));  //False
19             Console.WriteLine(object.ReferenceEquals(c1, c4));  //False
20             Console.WriteLine(object.ReferenceEquals(c3, c4));  //False
21             Console.WriteLine(object.ReferenceEquals(c5, c4));  //False

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.