C# 运算符核心用法解析
运算符是 C# 中用于执行特定计算或逻辑判断的符号。本文系统梳理各类运算符的行为特征与实际应用场景。
算术运算
一元运算符包含自增与自减两种形式,其前后缀位置直接影响返回值:
int baseVal = 5;
int postfix = baseVal++; // postfix 为 5,baseVal 变为 6
int prefix = ++baseVal; // prefix 为 7,baseVal 变为 7
int decrement = 3;
Console.WriteLine(--decrement); // 输出 2
Console.WriteLine(decrement--); // 输出 2,此后值为 1
二元算术运算符支持复合赋值形式:
int score = 50;
score += 25; // 等价于 score = score + 25
score *= 2; // 乘法复合赋值
score %= 7; // 取模后赋值
比较与关系运算
| 运算符 | 含义 | 示例(m=3, n=5) |
|---|---|---|
| == | 等于 | m == n 结果为 false |
| != | 不等于 | m != n 结果为 true |
| < | 小于 | m < n 结果为 true |
| > | 大于 | m > n 结果为 false |
| <= | 小于等于 | m <= 3 结果为 true |
| >= | 大于等于 | n >= 6 结果为 false |
逻辑运算
条件逻辑运算符具有短路特性,能提升执行效率:
bool flagA = true, flagB = false;
// & 与 && 的差异:前者始终计算两边,后者左侧为 false 时跳过右侧
bool result1 = flagA & flagB; // false,两边都执行
bool result2 = flagA && flagB; // false,flagB 仍被求值
// || 短路示例
bool result3 = flagA || SomeMethod(); // SomeMethod 不会被执行
// 异或:两操作数不同时返回 true
bool xorResult = flagA ^ flagB; // true
位运算与移位
位运算直接操作二进制位,适用于底层协议处理:
byte flags = 0b_0000_1101;
// 按位取反
byte inverted = (byte)~flags; // 0b_1111_0010
// 按位与、或、异或
byte mask = 0b_0000_1111;
byte masked = (byte)(flags & mask); // 保留低四位:0b_0000_1101
// 移位运算
uint data = 0b_0000_0001;
uint shifted = data << 4; // 0b_0001_0000,左移四位
// 算术右移与逻辑右移的区别
int negative = -16;
int arithShift = negative >> 2; // 保持符号位,结果为 -4
int logicalShift = negative >>> 2; // 高位补零,结果为正数
演示带符号与无符号右移的差异:
int sample = -1024;
Console.WriteLine($"原始值: {sample}, 二进制: {Convert.ToString(sample, 2)}");
int afterArith = sample >> 4;
int afterLogic = sample >>> 4;
Console.WriteLine($"算术右移: {afterArith}");
Console.WriteLine($"逻辑右移: {afterLogic}, 二进制: {Convert.ToString(afterLogic, 2).PadLeft(32, '0')}");
赋值与复合赋值
除基本赋值外,C# 提供丰富的复合赋值运算符:
int accumulator = 100;
accumulator += 50; // 加法复合
accumulator <<= 2; // 左移复合,等价于 accumulator = accumulator << 2
accumulator &= 0xFF; // 按位与复合
accumulator ^= 0xAA; // 按位异或复合
特殊运算符
空值相关
string? nullableRef = null;
string fallback = nullableRef ?? "default"; // 空合并运算符
// 空条件访问
int? length = nullableRef?.Length; // nullableRef 为 null 时 length 也为 null
// 空合并赋值
nullableRef ??= "initialized"; // 仅当左侧为 null 时赋值
类型与反射
// 获取类型信息
Type intType = typeof(int);
Type streamType = typeof(System.IO.Stream);
// 运行时类型检查
object obj = "test string";
if (obj is string text)
{
Console.WriteLine($"字符串长度: {text.Length}");
}
// 安全类型转换
var converted = obj as System.Collections.Generic.List<int>; // 失败返回 null
三元条件
int temperature = 28;
string status = temperature > 30 ? "炎热" : "舒适"; // 结果为 "舒适"
// 嵌套三元(建议控制嵌套层数)
int grade = 85;
char level = grade >= 90 ? 'A' : grade >= 80 ? 'B' : 'C';
sizeof 与内存布局
Console.WriteLine($"int 占用: {sizeof(int)} 字节");
Console.WriteLine($"long 占用: {sizeof(long)} 字节");
Console.WriteLine($"bool 占用: {sizeof(bool)} 字节");
// 非托管类型可用 sizeof
unsafe
{
Console.WriteLine($"指针大小: {sizeof(int*)}");
}