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