C# 初學者/運算子
外觀
< C# 初學者
運算子對資料執行操作。C# 中有三種類型的運算子
- 一元運算子的形式為
[運算子][物件]。例如,取反運算子:-number會返回帶相反符號的number(如果number為 12,則會返回 -12)。 - 二元運算子的形式為
[物件 1] [運算子] [物件 2]。例如,賦值運算子:number = 1234將number設定為 1234。 - 三元運算子作用於三個物件。C# 只有一個三元運算子,即條件運算子:
number == 1234 ? "good" : "bad"如果number等於 1234,則會返回 "good",否則返回 "bad"。
您可以幾乎以任何您喜歡的方式組合運算子。以下是一個包含許多不同運算子的示例
class OperatorsExample
{
public static void Main()
{
int number = 0;
float anotherNumber = 1.234;
string someText = "lots of ";
number = number + 4; // number is now 4
anotherNumber += 2; // this is a shorter version of the above; it adds 2 to anotherNumber, making it 3.234
someText += "text"; // someText now contains "lots of text"
number = -number; // number is now -4
anotherNumber -= number * 2; // subtracts -8 from anotherNumber, making anotherNumber 11.234.
number++; // increments number, making it -3
anotherNumber = number++; // increments number but sets anotherNumber to the original number.
// number is now -2, and anotherNumber is -3.
number--; // decrements number, making it -3
anotherNumber = --number; // decrements number and sets anotherNumber to the new number.
anotherNumber = number = 1; // sets both anotherNumber and number to 1.
bool someBoolean;
// sets someBoolean to true if anotherNumber equals number, otherwise sets it to false
someBoolean = anotherNumber == number;
}
}
++ 和 -- 運算子可以放在變數之前(字首)或之後(字尾)。兩者之間存在細微差異;如果放在前面,則先遞增或遞減,然後返回新值;如果放在後面,則先遞增或遞減,然後返回舊值。例如
int x, y;
x = 0;
x++;
++x;
// x is now 2...
y = x++; // y is now 2, x is now 3
x = 2; // x is now 2 again...
y = ++x; // y is now 3, x is now 3