复合赋值运算符的语法较短,可以分配结果。在将结果分配给第一个操作数之前,对两个操作数执行该操作。
以下是C#中的复合赋值运算符。
序号 | 运算符和运算符名称 |
---|---|
1 | + = 加法分配 |
2 | -= 减法分配 |
3 | * = 乘法分配 |
4 | / = 部门分配 |
5 | %= 模分配 |
6 | &= 按位与分配 |
7 | | = 按位或分配 |
8 | ^ = 按位XOR分配 |
9 | << = 左移分配 |
10 | >> = 右移分配 |
11 | => Lambda运算符 |
让我们看一个示例,以了解如何在C#中使用复合赋值运算符。
using System; namespace Program { class MyClass { public static void Main(string[] args) { int val = 7; val += 3; Console.WriteLine("Addition Assignment: " + val); val -= 2; Console.WriteLine("Subtraction Assignment: " + val); val *= 7; Console.WriteLine("Multiplication Assignment: " + val); val /= 7; Console.WriteLine("Division Assignment: " + val); val %= 5; Console.WriteLine("Modulo Assignment: " + val); val &= 9; Console.WriteLine("Bitwise And Assignment: " + val); val <<= 3; Console.WriteLine("Left Shift Assignment: " + val); val >>= 5; Console.WriteLine("Right Shift Assignment: " + val); } } }
输出结果
Addition Assignment: 10 Subtraction Assignment: 8 Multiplication Assignment: 56 Division Assignment: 8 Modulo Assignment: 3 Bitwise And Assignment: 1 Left Shift Assignment: 8 Right Shift Assignment: 0