C# 運算子三種:一元、二元、三元。所謂二元即參與運算變數有兩個。
+、-、++、--。例:int x = 10; int x1 = +x; int x2 = -x; 則 x1 = 10; x2 = -10。
加、減、乘、除、取餘,符號 +、-、*、/、%。前四不贅述。重點學取餘:x = 42 % 10; // x = 2,原理同數學取模。int y = 81 % 9; // y = 0。
+ 在字串中可串接:
string str1 = "hello";
string str2 = "你好";
string str3 = str1 + str2;
Console.WriteLine("str3 = str1 + str2: {0}", str3);
輸出:str3 = hello你好。
++、-- 在迴圈大用途。++ 作用值 +1,-- 值 -1。但賦值過程中:int a = 10; int b = ++a; int c = a++; 則 b、c 不相等。
int a = 10;
int a1 = a;
int b = ++a; // 先自增再賦值
int c = a++; // 先賦值再自增
Console.WriteLine("b = ++a : {0}", b); // 11
Console.WriteLine("c = a++ : {0}", c); // 11 (此時 a 已為 11)
總結:++/-- 在前 → 先自增/減再賦值;在後 → 先賦值再自增/減。
主要:=、+=、-=、*=、/=、%=。= 簡單,將同型別變數值賦給另一個。其餘四個原理相同:
int x1 = 11, x2 = 12, x3 = x1;
x1 += x2; // x1 = x1 + x2 = 23
x2 -= x3; // x2 = x2 - x3 = 1
Console.WriteLine("x1 += x2 後 x1 = {0}", x1);
Console.WriteLine("x2 -= x3 後 x2 = {0}", x2);
*=、/= 同理。Console.WriteLine("x1 *= x2 後 x1 = {0}", x1); 中 {0} 為格式化輸出佔位符,可多參數:Console.WriteLine("x1={0}, x2={1}, x3={2}", x1, x2, x3);。