C# - 赋值运算符



C# 支持以下赋值运算符:

运算符 描述 示例
= 简单赋值运算符,将右侧操作数的值赋给左侧操作数 C = A + B 将 A + B 的值赋给 C
+= 加法赋值运算符,它将右侧操作数加到左侧操作数上,并将结果赋给左侧操作数 C += A 等价于 C = C + A
-= 减法赋值运算符,它将右侧操作数从左侧操作数中减去,并将结果赋给左侧操作数 C -= A 等价于 C = C - A
*= 乘法赋值运算符,它将右侧操作数乘以左侧操作数,并将结果赋给左侧操作数 C *= A 等价于 C = C * A
/= 除法赋值运算符,它将左侧操作数除以右侧操作数,并将结果赋给左侧操作数 C /= A 等价于 C = C / A
%= 取模赋值运算符,它使用两个操作数进行取模运算,并将结果赋给左侧操作数 C %= A 等价于 C = C % A
<<= 左移赋值运算符 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

示例

以下示例演示了 C# 中所有可用的赋值运算符:

using System;

namespace OperatorsAppl {

   class Program {
   
      static void Main(string[] args) {
         int a = 21;
         int c;
         c = a;
         Console.WriteLine("Line 1 - =  Value of c = {0}", c);
         
         c += a;
         Console.WriteLine("Line 2 - += Value of c = {0}", c);
         
         c -= a;
         Console.WriteLine("Line 3 - -=  Value of c = {0}", c);
         
         c *= a;
         Console.WriteLine("Line 4 - *=  Value of c = {0}", c);
         
         c /= a;
         Console.WriteLine("Line 5 - /=  Value of c = {0}", c);
         
         c = 200;
         c %= a;
         Console.WriteLine("Line 6 - %=  Value of c = {0}", c);
         
         c <<= 2;
         Console.WriteLine("Line 7 - <<=  Value of c = {0}", c);
         
         c >>= 2;
         Console.WriteLine("Line 8 - >>=  Value of c = {0}", c);
         
         c &= 2;
         Console.WriteLine("Line 9 - &=  Value of c = {0}", c);
         
         c ^= 2;
         Console.WriteLine("Line 10 - ^=  Value of c = {0}", c);
         
         c |= 2;
         Console.WriteLine("Line 11 - |=  Value of c = {0}", c);
         Console.ReadLine();
      }
   }
}

编译并运行上述代码后,将产生以下结果:

Line 1 - = Value of c = 21
Line 2 - += Value of c = 42
Line 3 - -= Value of c = 21
Line 4 - *= Value of c = 441
Line 5 - /= Value of c = 21
Line 6 - %= Value of c = 11
Line 7 - <<= Value of c = 44
Line 8 - >>= Value of c = 11
Line 9 - &= Value of c = 2
Line 10 - ^= Value of c = 0
Line 11 - |= Value of c = 2
csharp_operators.htm
广告