Skip to content

C# - While循环

while 循环是 C# 中一种基本的控制流语句,只要给定的布尔条件评估为 true,它就会重复执行一段代码。它非常适用于在循环开始前不知道迭代次数的情况。

while 循环的语法很简单:

while (condition) {
// Code to be executed as long as the condition is true
}

这里,statement(s) 可以是单个语句,也可以是括在花括号 {} 中的语句块。condition 是一个布尔表达式。只要条件为 true,循环就会继续迭代。当条件变为 false 时,程序将继续执行循环后面的行。

while 循环的执行流程可以如下可视化:

+--------------------+
| |
| 检查条件 |
| |
+---------+----------+
|
(条件为真) (条件为假)
| |
+---------v----------+ |
| | |
| 执行循环体 | |
| | |
+--------------------+ |
| |
+--------------------+-----> [循环结束]

一个关键特点是 while 循环是一个前置测试循环。条件在循环体执行之前进行检查。这意味着如果条件最初为 false,循环体将一次也不会执行。

让我们看一个打印从 1 到 5 的数字的简单示例。

using System;
class WhileLoopExample {
static void Main() {
// 1. 初始化
int counter = 1;
// 2. 条件
while (counter <= 5) {
Console.WriteLine($"当前计数: {counter}");
// 3. 更新(递增)
// 这一步对于防止无限循环至关重要!
counter++;
}
Console.WriteLine("循环已完成。");
}
}

编译并执行上述代码后,它会产生以下结果:

Current count: 1
Current count: 2
Current count: 3
Current count: 4
Current count: 5
Loop finished.

while 循环非常适合重复提示用户直到他们提供有效输入。

using System;
class InputValidation {
static void Main() {
int age;
Console.Write("Please enter your age (a positive number): ");
// Loop while the input is not a valid integer OR the parsed number is not positive.
while (!int.TryParse(Console.ReadLine(), out age) || age <= 0) {
Console.ForegroundColor = ConsoleColor.Red;
Console.Write("Invalid input. Please enter a valid positive number for age: ");
Console.ResetColor();
}
Console.WriteLine($"Thank you! You entered age: {age}");
}
}

while 循环非常适合逐行读取文件直到文件末尾。现代 C# 可以异步完成此操作。

using System;
using System.IO;
using System.Threading.Tasks;
class FileProcessor {
static async Task Main() {
string filePath = "data.txt";
// 确保存在一个示例文件
await File.WriteAllTextAsync(filePath, "第一行。\n第二行。\n文件末尾。");
Console.WriteLine($"正在从 {filePath} 读取...");
try {
using (var reader = new StreamReader(filePath)) {
string line;
// 只要 ReadLineAsync() 返回非空字符串,循环就会继续
while ((line = await reader.ReadLineAsync()) != null) {
Console.WriteLine(line);
}
}
} catch (FileNotFoundException) {
Console.WriteLine($"错误: 文件 '{filePath}' 未找到。");
}
File.Delete(filePath); // 清理示例文件
}
}

在游戏开发中,while 循环通常构成核心游戏循环,只要游戏处于活动状态,它就会运行。

using System;
class GameLoop {
static void Main() {
bool isGameRunning = true;
int score = 0;
while (isGameRunning) {
Console.WriteLine("\n--- 主菜单 ---");
Console.WriteLine("1. 玩一局");
Console.WriteLine("2. 退出");
Console.Write("请输入您的选择: ");
string choice = Console.ReadLine();
if (choice == "1") {
score += 10;
Console.WriteLine($"您玩了一局!您的分数现在是: {score}");
} else if (choice == "2") {
isGameRunning = false; // 这将导致循环终止
} else {
Console.WriteLine("无效的选择,请重试。");
}
}
Console.WriteLine("感谢您的游玩!");
}
}

无限循环: while 循环最常见的错误是创建无限循环。当循环条件永远不会变为 false 时,就会发生这种情况。

// 危险: 无限循环
int i = 0;
while (i < 5) {
Console.WriteLine("这将永远运行!");
// 更新语句 'i++;' 缺失。
}

调试技巧: 如果您的控制台应用程序挂起,很可能是进入了无限循环。使用 IDE 的调试器在循环内部设置断点。逐步执行代码以检查条件中涉及的变量,并查看它们为何未按预期更改。