跳到主要内容

C# 运算符

本章将介绍 C# 中的各种运算符,包括算术、比较、逻辑、位运算等。

算术运算符

int a = 10;
int b = 3;

// 基本运算
Console.WriteLine(a + b); // 13 加法
Console.WriteLine(a - b); // 7 减法
Console.WriteLine(a * b); // 30 乘法
Console.WriteLine(a / b); // 3 除法(整数除法)
Console.WriteLine(a % b); // 1 取余

整数除法 vs 浮点除法

int a = 10;
int b = 3;
double c = 3.0;

Console.WriteLine(a / b); // 3 (整数除法,结果为 int)
Console.WriteLine(a / c); // 3.333... (浮点除法,结果为 double)
Console.WriteLine((double)a / b); // 3.333... (强制转换后再除)

自增自减运算符

int a = 5;

// 前置递增:先增后用
Console.WriteLine(++a); // 6,先把 a 变成 6,然后输出

// 后置递增:先用后增
a = 5;
Console.WriteLine(a++); // 5,先输出 5,然后 a 变成 6

// 前置递减和后置递减同理
int b = 5;
Console.WriteLine(--b); // 4
Console.WriteLine(b--); // 4

复合赋值运算符

int x = 10;

x += 5; // x = x + 5 = 15
x -= 3; // x = x - 3 = 12
x *= 2; // x = x * 2 = 24
x /= 4; // x = x / 4 = 6
x %= 5; // x = x % 5 = 1

比较运算符

int a = 10;
int b = 20;

Console.WriteLine(a == b); // False 等于
Console.WriteLine(a != b); // True 不等于
Console.WriteLine(a > b); // False 大于
Console.WriteLine(a < b); // True 小于
Console.WriteLine(a >= b); // False 大于等于
Console.WriteLine(a <= b); // True 小于等于

逻辑运算符

bool x = true;
bool y = false;

// 逻辑与(AND)
Console.WriteLine(x && y); // False,两边都为 true 才为 true

// 逻辑或(OR)
Console.WriteLine(x || y); // True,一边为 true 就为 true

// 逻辑非(NOT)
Console.WriteLine(!x); // False,取反

// 逻辑异或(XOR)
Console.WriteLine(x ^ y); // True,两边不同为 true,相同为 false

短路特性

bool result = false && (1/0 == 0);  // False,&& 短路,不会计算右边
bool result2 = true || (1/0 == 0); // True,|| 短路,不会计算右边

位运算符

int a = 5;   // 二进制:0101
int b = 3; // 二进制:0011

Console.WriteLine(a & b); // 1 (0001) 按位与
Console.WriteLine(a | b); // 7 (0111) 按位或
Console.WriteLine(a ^ b); // 6 (0110) 按位异或
Console.WriteLine(~a); // -6 按位取反
Console.WriteLine(a << 1); // 10 (1010) 左移1位
Console.WriteLine(a >> 1); // 2 (0010) 右移1位

位运算示例

// 判断奇偶
int num = 7;
bool isOdd = (num & 1) == 1;

// 快速乘除2
int n = 10;
int doubleN = n << 1; // 乘2
int halfN = n >> 1; // 除2

// 设置特定位
int flags = 0; // 0000
flags |= 1 << 2; // 设置第3位为1 -> 0100

// 清除特定位
flags &= ~(1 << 2); // 清除第3位

// 切换特定位
flags ^= 1 << 2; // 切换第3位

三元运算符

// 语法:condition ? valueIfTrue : valueIfFalse
int age = 20;
string result = age >= 18 ? "成年人" : "未成年人";

// 嵌套使用(不推荐,可读性差)
string grade = score >= 90 ? "A" : (score >= 80 ? "B" : "C");

空合并运算符

// ?? 运算符:左边为 null 时使用右边的值
string name = null;
string displayName = name ?? "匿名用户"; // "匿名用户"

string? nullableName = null;
string nonNullName = nullableName ?? "默认值";

// ??= 运算符(C# 8+)
string? s = null;
s ??= "默认值"; // 如果 s 为 null,则赋值为 "默认值"
Console.WriteLine(s); // "默认值"

typeof 运算符

// 获取类型信息
Type t = typeof(int);
Console.WriteLine(t.Name); // Int32
Console.WriteLine(t.FullName); // System.Int32

sizeof 运算符

// 获取类型大小(字节)
Console.WriteLine(sizeof(int)); // 4
Console.WriteLine(sizeof(long)); // 8
Console.WriteLine(sizeof(double)); // 8

// 非托管类型需要 unsafe 上下文
unsafe
{
Console.WriteLine(sizeof(MyStruct));
}

nameof 运算符(C# 6+)

// 获取变量、类型、成员的名称字符串
string name = nameof(Console.WriteLine); // "WriteLine"
string className = nameof(List<int>); // "List"
string propName = nameof(DateTime.Now); // "Now"

// 使用示例:参数验证
void SetName(string name)
{
if (string.IsNullOrEmpty(name))
throw new ArgumentException("名称不能为空", nameof(name));
}

运算符优先级

如果不确定优先级,使用括号明确:

// 优先级示例
int result = 2 + 3 * 4; // 14,先算乘法
int result2 = (2 + 3) * 4; // 20,先算加法
优先级运算符结合性
1()-
2!、~、++、--、typeof、sizeof右到左
3*、/、%左到右
4+、-左到右
5<<、>>左到右
6<、>、<=、>=、is、as左到右
7==、!=左到右
8&左到右
9^左到右
10|左到右
11&&左到右
12||左到右
13??左到右
14?:右到左
15=、+=、-=、*=、/=、%=、&=、|=、^=、<<=、>>=右到左

溢出检查

checked 关键字

int max = int.MaxValue;
Console.WriteLine(max); // 2147483647

// 默认:整数溢出静默发生(环绕行为)
int overflow = max + 1; // -2147483648

// checked:抛出 OverflowException
checked
{
int overflow2 = max + 1; // 抛出异常
}

unchecked 关键字

unchecked
{
int overflow = int.MaxValue + 1; // 允许溢出,不抛出异常
}

运算符重载

// 定义运算符重载
struct Vector
{
public double X { get; set; }
public double Y { get; set; }

public Vector(double x, double y)
{
X = x;
Y = y;
}

// 重载 + 运算符
public static Vector operator +(Vector a, Vector b)
{
return new Vector(a.X + b.X, a.Y + b.Y);
}

// 重载 - 运算符
public static Vector operator -(Vector a, Vector b)
{
return new Vector(a.X - b.X, a.Y - b.Y);
}
}

// 使用
Vector v1 = new Vector(1, 2);
Vector v2 = new Vector(3, 4);
Vector v3 = v1 + v2; // (4, 6)

小结

  1. 算术运算符:+、-、*、/、%、++、--
  2. 比较运算符:==、!=、>、<、>=、<=
  3. 逻辑运算符:&&、||、!、^
  4. 位运算符:&、|、^、~、<<、>>
  5. 特殊运算符:三元运算符、??、nameof
  6. 溢出处理:checked/unchecked

练习

  1. 写一个程序,判断一个数是否为2的幂次方
  2. 使用位运算实现两个数的交换(不使用临时变量)
  3. 创建一个复数结构体,重载 +、- 运算符
  4. 使用 ?? 运算符处理可能为 null 的用户输入