C# 中的复合赋值运算符
复合赋值运算符具有更短的语法来分配结果。在将结果分配给第一个操作数之前,对两个操作数执行运算。
以下是 C# 中的复合赋值运算符。
序号 | 运算符 & 运算符名称 |
---|---|
1 | += 加法赋值 |
2 | -= 减法赋值 |
3 | *= 乘法赋值 |
4 | /= 除法赋值 |
5 | %= 模赋值 |
6 | &= 按位 AND 赋值 |
7 | |= 按位 OR 赋值 |
8 | ^= 按位异或赋值 |
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
广告