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