Z
ZHANK
入门基础

运算符

算术/比较/逻辑运算符、??/??= 空合并、?. 空条件、nameof/is/as

运算符

C# 运算符丰富了经典的 C 系运算符,加入了 ?? 空合并、?. 空条件、nameof 等现代特性。

学完本章你将: 掌握算术/比较/逻辑运算符、??/??=、?. 、nameof/is/as。


基本运算符

csharp
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

// 注意:整数除法截断,需要浮点就转换
Console.WriteLine((double)a / b);  // 3.333...

?? / ??= / ?. —— C# 的空安全三件套

csharp
// ?? 空合并:左边为 null 时取右边
string name = null;
string display = name ?? "匿名";  // "匿名"

// ??= 空合并赋值:只在为 null 时赋值
name ??= "默认值";

// ?. 空条件:不为 null 才继续访问
string text = null;
int? len = text?.Length;  // null(而不是 NullReferenceException!)
int len2 = text?.Length ?? 0;  // 0

// ?[] 空条件索引
int? first = arr?[0];

nameof / is / as

csharp
// nameof —— 获取变量/类型名字符串(重构安全!)
string propName = nameof(person.Name);  // "Name"

// is —— 类型检查 + 模式匹配
if (obj is string s)  // 检查 + 赋值一步完成
    Console.WriteLine(s.Length);

// as —— 安全类型转换(失败返回 null 而非异常)
var str = obj as string;
if (str != null) { /* 使用 str */ }