加法運算子:++=

內建的整數浮點數數字型別,字串型別和委派型別均支援 ++=運算子。

如需算術 + 運算子的資訊,請參閱算術運算子一文中的一元加號和減號運算子加法運算子 + 章節。

字串串連

當其中一或兩個運算元的型別為 字串 時,+ 運算子會串連其運算元的字串表示 (null 的字串表示法為空字串):

Console.WriteLine("Forgot" + "white space");
Console.WriteLine("Probably the oldest constant: " + Math.PI);
Console.WriteLine(null + "Nothing to add.");
// Output:
// Forgotwhite space
// Probably the oldest constant: 3.14159265358979
// Nothing to add.

字串插補提供更便利的方式進行字串格式設定:

Console.WriteLine($"Probably the oldest constant: {Math.PI:F2}");
// Output:
// Probably the oldest constant: 3.14

從 C# 10 開始,當用於預留位置的所有運算式也是常數字串時,您可以使用字串插補來初始化常數字串。

從 C# 11 開始,+運算子會執行 UTF-8 常值字串的字串串連。 此運算子會串連兩個 ReadOnlySpan<byte> 物件。

委派組合

針對相同委派型別中的運算元,+ 運算子會傳回新的委派執行個體,並在叫用時叫用左側運算元,然後叫用右側運算元。 如果其中任一個運算元為 null,則 + 運算子會傳回另一個運算元的值 (也有可能是 null)。 下列範例顯示委派如何與 + 運算子結合:

Action a = () => Console.Write("a");
Action b = () => Console.Write("b");
Action ab = a + b;
ab();  // output: ab

若要執行委派移除,請使用 - 運算子

如需委派型別的詳細資訊,請參閱委派

加法指派運算子 +=

使用 += 運算子的運算式,例如

x += y

相當於

x = x + y

但只會評估 x 一次。

下列範例示範 += 運算子的用法:

int i = 5;
i += 9;
Console.WriteLine(i);
// Output: 14

string story = "Start. ";
story += "End.";
Console.WriteLine(story);
// Output: Start. End.

Action printer = () => Console.Write("a");
printer();  // output: a

Console.WriteLine();
printer += () => Console.Write("b");
printer();  // output: ab

當您訂閱事件時,您也會使用 += 來指定事件處理常式方法。 如需詳細資訊,請參閱如何:訂閱及取消訂閱事件

運算子是否可多載

使用者定義型別可以多載+ 運算子。 多載二元 + 運算子時,+= 運算子也會隱含地多載。 使用者定義型別無法明確地多載 += 運算子。

C# 語言規格

如需詳細資訊,請參閱 C# 語言規格一元加號運算子加法運算子小節。

另請參閱