运算符是一个符号,告诉编译器执行特定的数学或逻辑操作。
以下是C#中的赋值运算符。
运算符 | 描述 | 例 |
---|---|---|
= | 简单的赋值运算符,将值从右侧操作数分配到左侧操作数 | C = A + B将A + B的值赋给C |
+ = | 添加AND赋值运算符,它将右操作数添加到左操作数,并将结果分配给左操作数 | C + = A等于C = C + A |
-= | 减去AND赋值运算符,它从左操作数中减去右操作数,并将结果赋给左操作数 | C-= A等效于C = C-A |
* = | 将AND赋值运算符相乘,将右操作数与左操作数相乘并将结果分配给左操作数 | C * = A等效于C = C * A |
/ = | 除法AND赋值运算符,它将左操作数除以右操作数,并将结果分配给左操作数 | C / = A等于C = C / A |
%= | 模AND赋值运算符,它使用两个操作数取模并将结果赋给左操作数 | C%= A等于C = C%A |
<< = | 左移AND赋值运算符 | C << = 2与C = C << 2相同 |
>> = | 右移和赋值运算符 | C >> = 2与C = C >> 2相同 |
&= | 按位与赋值运算符 | C&= 2与C = C&2相同 |
^ = | 按位异或与赋值运算符 | C ^ = 2与C = C ^ 2相同 |
| = | 按位或运算符和赋值运算符 | C | = 2与C = C |相同 2 |
using System; namespace Demo { class Program { static void Main(string[] args) { int a = 21; int c; c = a; Console.WriteLine("Value of c = {0}", c); c += a; Console.WriteLine("Value of c = {0}", c); c -= a; Console.WriteLine("Value of c = {0}", c); c *= a; Console.WriteLine("Value of c = {0}", c); c /= a; Console.WriteLine("Value of c = {0}", c); c = 200; c %= a; Console.WriteLine("Value of c = {0}", c); c <<= 2; Console.WriteLine("Value of c = {0}", c); c >>= 2; Console.WriteLine("Value of c = {0}", c); c &= 2; Console.WriteLine("Value of c = {0}", c); c ^= 2; Console.WriteLine("Value of c = {0}", c); c |= 2; Console.WriteLine("Value of c = {0}", c); Console.ReadLine(); } } }
输出结果
Value of c = 21 Value of c = 42 Value of c = 21 Value of c = 441 Value of c = 21 Value of c = 11 Value of c = 44 Value of c = 11 Value of c = 2 Value of c = 0 Value of c = 2