字符串對象是不可變的:即它們創建之后就無法更改。所有看似修改字符串的 String 方法和 C# 運算符實際上都以新字符串對象的形式返回結果。
在下面的示例中,當連接 s1 和 s2 的內容以形成一個字符串時,不會修改兩個原始字符串。+= 運算符會創建一個包含組合內容的新字符串。這個新對象賦給變量 s1,而最初賦給 s1 的對象由于沒有其他任何變量包含對它的引用而釋放,用于垃圾回收。
string s1 = "A string is more ";
string s2 = "than the sum of its chars.";
// Concatenate s1 and s2. This actually creates a new
// string object and stores it in s1, releasing the
// reference to the original object.
s1 += s2;
System.Console.WriteLine(s1);
// Output: A string is more than the sum of its chars.
由于“修改”字符串實際上是創建新字符串,因此創建對字符串的引用時必須謹慎。
如果創建了對字符串的引用,然后“修改”原始字符串,則該引用指向的仍是原始對象,而不是修改字符串時創建的新對象。下面的代碼說明了這種行為:
string s1 = "Hello ";
string s2 = s1;
s1 += "World";
System.Console.WriteLine(s2);
//輸出: Hello
新聞熱點
疑難解答