C# 运算符(Operators)全面详解
                           
天天向上
发布: 2025-04-13 12:58:10

原创
736 人浏览过

本章节会从专业开发工程师的角度,从语言规范、分类、使用方式、示例代码、注意事项、官方文档链接等维度,全面详解 C# 运算符,并提供多种应用场景和实践建议。


一、什么是运算符?

运算符是对变量或值执行运算的符号。在 C# 中,运算符按功能划分为不同类别,例如算术运算符、比较运算符、逻辑运算符、赋值运算符、位运算符等。

参考文档:
🔗 Microsoft Docs – C# Operators and Expressions


二、C# 运算符分类总览

类型示例说明
算术运算符+, -, *, /, %加、减、乘、除、取余
赋值运算符=, +=, -=, *=, /=赋值与简写赋值
比较运算符==, !=, <, >, <=比较两个值
逻辑运算符&&, ||, !与、或、非
位运算符&, |, ^, ~, <<, >>位级别的运算
递增/递减运算符++, --自增、自减
条件(三元)运算符?:条件判断表达式
空合并运算符??, ??=null 值处理
类型检查与转换is, as, typeof, sizeof, cast类型判断与转换
其他运算符=>, ??, =>, [], ()表达式、委托、索引器等

三、各类运算符详解

1️⃣ 算术运算符(Arithmetic)

int a = 10, 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

2️⃣ 赋值运算符(Assignment)

int x = 5;
x += 3;   // x = x + 3;
x *= 2;   // x = x * 2;

支持:=, +=, -=, *=, /=, %=, &=, |=, ^=, <<=, >>=


3️⃣ 比较运算符(Comparison)

int a = 5, b = 6;
bool isEqual = (a == b);  // false
bool notEqual = (a != b); // true
bool greater = (a > b);   // false

4️⃣ 逻辑运算符(Logical)

bool t = true, f = false;
Console.WriteLine(t && f); // false
Console.WriteLine(t || f); // true
Console.WriteLine(!t);     // false

5️⃣ 位运算符(Bitwise)

int a = 5;   // 0101
int b = 3;   // 0011
Console.WriteLine(a & b); // 0001 => 1
Console.WriteLine(a | b); // 0111 => 7
Console.WriteLine(a ^ b); // 0110 => 6
Console.WriteLine(~a);    // 取反,结果依赖于整型大小
Console.WriteLine(a << 1); // 左移:10
Console.WriteLine(b >> 1); // 右移:1

6️⃣ 条件运算符(三元)

int score = 90;
string grade = score >= 60 ? "及格" : "不及格";

7️⃣ 空合并运算符(Null-Coalescing)

string name = null;
string displayName = name ?? "匿名用户"; // 如果 name 为 null,则用默认值
string? input = null;
input ??= "默认值";  // 如果为 null,就赋默认值

8️⃣ 类型运算符

object obj = "Hello";
if (obj is string) {
    Console.WriteLine("是字符串");
}

string? str = obj as string; // 成功则转换,失败返回 null

Console.WriteLine(typeof(int));        // System.Int32
Console.WriteLine(sizeof(int));        // 4 (仅限 unsafe 或编译时常量类型)

四、运算符优先级(Precedence)

高优先级先执行,常见规则如下(从高到低):

  1. () 括号
  2. 一元运算符(++, --, !, ~
  3. 乘除取余(*, /, %
  4. 加减(+, -
  5. 移位(<<, >>
  6. 比较(<, >, <=, >=
  7. 相等(==, !=
  8. 位与、或、异或(&, |, ^
  9. 逻辑与/或(&&, ||
  10. 条件运算符(?:
  11. 赋值运算符(=, +=, -=

五、自定义运算符(Operator Overloading)

C# 支持在类中重载部分运算符:

public class Point {
    public int X, Y;

    public static Point operator +(Point a, Point b) {
        return new Point { X = a.X + b.X, Y = a.Y + b.Y };
    }
}
var p1 = new Point { X = 1, Y = 2 };
var p2 = new Point { X = 3, Y = 4 };
var result = p1 + p2;  // 调用自定义的 +

📘 官方文档:
🔗 Microsoft Docs – Operator Overloading


六、常见错误与陷阱

错误说明
/ 运算整数除法结果是整数,要用浮点类型防止截断
==.Equals() 的误用对于引用类型建议使用 .Equals()
as 用于值类型无效,值类型不能用 as
运算符重载滥用会造成代码难以理解,需合理设计

七、C# 运算符完整官方文档目录(推荐收藏)


八、补充建议

  • ✔️ 推荐在逻辑表达式中优先使用括号明确意图
  • ✔️ 了解每类运算符的行为和返回值类型(特别是布尔、位运算)
  • ✔️ 避免不清晰的链式赋值
  • ✔️ 使用 Rider/VSCode 提示辅助写出更清晰的逻辑

更多详细内容请关注其他相关文章!

发表回复 0

Your email address will not be published. Required fields are marked *