31. C#(continue)
发布: (2026年3月11日 GMT+8 02:43)
3 分钟阅读
原文: Dev.to
Source: Dev.to
0. continue 的本质
continue 会立即停止当前迭代并进入下一次。
- ❌ 它 不会终止 循环。
- ✅ 它只 跳过当前循环。
执行会直接跳到下一次迭代。
1. 简单示例 — 跳过 3 的倍数
目标
打印 0 到 20 的数字,但 排除 3 的倍数。
完整可运行代码
using System;
class Program
{
static void Main()
{
for (int i = 0; i 10 or type 'stop':");
input = Console.ReadLine();
if (input == "stop")
{
break;
}
bool isNumeric = true;
foreach (char c in input)
{
if (!char.IsDigit(c))
{
isNumeric = false;
break;
}
}
if (!isNumeric)
{
Console.WriteLine("Invalid input.");
continue; // skip parsing and restart loop
}
userNumber = int.Parse(input);
} while (userNumber <= 10);
Console.WriteLine("Loop ended.");
Console.ReadKey();
}
}
执行流程(用户输入 "abc")
isNumeric = false
continue executes
int.Parse is skipped
loop starts next iteration
结果:程序 不会崩溃。
4. 为什么 break 没有导致初始化错误
break 完全退出循环,因此循环内部 break 之后的任何代码都不会被执行。因此,编译器不要求仅在该点之后才会被赋值的变量一定已被确定赋值。
if (input == "stop")
{
break; // loop ends here
}
continue 不同之处
continue 跳回循环条件,这意味着循环体其余部分仍然是控制流的一部分。所有可能的执行路径都必须使变量保持有效状态,否则编译器会报错。
5. continue 何时有用
在以下情况下使用 continue:
- 存在许多无效条件
- 希望提前过滤
- 倾向于更简洁的控制流
典型模式:
if (invalidCondition)
{
continue; // skip to next iteration
}
// main logic below
这将 异常情况 与 正常执行 分离。
最终总结
break退出 整个循环。continue仅跳过当前迭代,并继续下一次。
选择与期望的控制流行为相匹配的关键字。