- C# 基础教程
- C# - 首页
- C# - 概述
- C# - 环境
- C# - 程序结构
- C# - 基本语法
- C# - 数据类型
- C# - 类型转换
- C# - 变量
- C# - 常量
- C# - 运算符
- C# - 决策
- C# - 循环
- C# - 封装
- C# - 方法
- C# - 可空类型
- C# - 数组
- C# - 字符串
- C# - 结构体
- C# - 枚举
- C# - 类
- C# - 继承
- C# - 多态
- C# - 运算符重载
- C# - 接口
- C# - 命名空间
- C# - 预处理器指令
- C# - 正则表达式
- C# - 异常处理
- C# - 文件 I/O
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
广告