if / else
if (x > 0)
{
Console.WriteLine("正");
}
else if (x == 0)
{
Console.WriteLine("零");
}
else
{
Console.WriteLine("负");
}
单语句可省花括号(但推荐永远写):
if (x > 0) Console.WriteLine("正");
三元运算符
var sign = x > 0 ? "正" : x < 0 ? "负" : "零";
switch 语句
switch (day)
{
case "Mon":
case "Tue":
Console.WriteLine("早");
break;
case "Sat":
case "Sun":
Console.WriteLine("周末");
break;
default:
Console.WriteLine("中间");
break;
}
每个 case 必须 break / return / throw / goto——没有 fallthrough(除非空 case 堆叠)。
switch 表达式(C# 8+,现代写法)
var description = day switch
{
"Mon" or "Tue" => "早",
"Sat" or "Sun" => "周末",
_ => "中间",
};
返回值、紧凑、穷举性检查(_ 是兜底)。新代码优先用这个。
详细模式见 第 17 篇。
for
for (int i = 0; i < 10; i++)
{
Console.WriteLine(i);
}
// 步长
for (int i = 0; i < 100; i += 5)
{
...
}
// 倒序
for (int i = 9; i >= 0; i--)
{
...
}
foreach
var nums = new[] { 1, 2, 3 };
foreach (var n in nums)
{
Console.WriteLine(n);
}
// 遍历字典
var d = new Dictionary<string, int> { ["a"] = 1, ["b"] = 2 };
foreach (var (k, v) in d)
{
Console.WriteLine($"{k}={v}");
}
任何实现 IEnumerable<T> 的都能 foreach——数组、List、Dictionary、HashSet、自家集合。
while / do-while
while (cond)
{
...
}
do
{
...
}
while (cond); // 注意结尾分号
break / continue
foreach (var x in items)
{
if (x.IsBad) continue; // 跳过本次
if (x.IsEnd) break; // 退出整个循环
Process(x);
}
goto + 标签
for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 10; j++)
{
if (matrix[i][j] == target)
{
goto found;
}
}
}
found:
Console.WriteLine("找到了");
跳出嵌套循环几乎是 goto 唯一合理用途。其他情况重构成方法 + early return。
switch 内的 goto case "x" / goto default 用来 fallthrough。
范围 / 索引(C# 8+)
var arr = new[] { 1, 2, 3, 4, 5 };
arr[^1]; // 5(末尾倒数第 1)
arr[^2]; // 4
arr[1..3]; // {2, 3}(左闭右开)
arr[..3]; // {1, 2, 3}
arr[2..]; // {3, 4, 5}
arr[..]; // 整个数组的副本
Range 和 Index 类型让切片像 Python。
try / catch / finally
try
{
DoRisky();
}
catch (FileNotFoundException ex)
{
Console.WriteLine($"文件没找到: {ex.FileName}");
}
catch (Exception ex) when (ex.Message.Contains("timeout")) // when 过滤
{
Console.WriteLine("超时了");
}
finally
{
Cleanup();
}
详见 第 19 篇异常。
using(资源自动释放)
// 旧风格
using (var file = File.OpenRead("data.txt"))
{
// 用 file
} // 出块自动 Dispose
// C# 8+ 简化
using var file = File.OpenRead("data.txt");
// 用 file
// file 在当前作用域结束时自动 Dispose
任何实现 IDisposable 的对象都能 using——文件、连接、socket 必带。
模式 + when
if 也能加 when(在 switch 表达式 / 语句里):
return user switch
{
{ Age: < 18 } => "未成年",
{ Age: >= 65 } => "老年",
{ Age: var a } when a >= 18 && a < 65 => "成年",
_ => "未知",
};
详见 第 17 篇。
→ 下一篇 方法