Skip to content

C# - Do While循环

do...while 循环是一种后测循环,这意味着它在每次执行循环体之后检查其条件。这产生了一个关键的保证:do...while 循环中的代码块将总是至少执行一次,无论循环条件最初是真还是假。

这使得它成为那些在评估条件之前必须执行某个操作的场景的完美选择,例如提示用户输入然后验证该输入。

do
{
// 要执行的语句;
// 此代码块总是至少运行一次。
}
while (condition);

控制流程:

1. 执行 `do` 语句内的代码块。
2. 评估 `while()` 中的布尔 `condition`。
3. 如果条件为 `true`(真),控制流跳回 `do` 语句,重复此过程。
4. 如果条件为 `false`(假),循环终止,程序继续执行循环后的下一条语句。
特性while 循环do...while 循环
测试类型前测循环后测循环
执行次数循环体可能执行零次或多次。循环体执行一次或多次。
常见用例当条件可能已为假时进行循环。当操作必须在检查前发生时进行循环。

do...while 循环的真正价值体现在其实际应用中。

这是最典型的例子。你必须首先获取输入,然后才能检查其是否有效。

using System;
class Program
{
static void Main()
{
int age;
do
{
Console.Write("Please enter your age (a positive number): ");
}
while (!int.TryParse(Console.ReadLine(), out age) || age <= 0);
Console.WriteLine($"Thank you. Your age is: {age}");
}
}

示例交互:

Please enter your age (a positive number): abc
Please enter your age (a positive number): -5
Please enter your age (a positive number): 25
Thank you. Your age is: 25

向用户显示一个选项菜单,并持续显示,直到他们选择退出。

using System;
class Program
{
static void Main()
{
string choice;
do
{
Console.WriteLine("\n--- MENU ---");
Console.WriteLine("1. Start New Game");
Console.WriteLine("2. Load Game");
Console.WriteLine("3. Options");
Console.WriteLine("4. Exit");
Console.Write("Enter your choice: ");
choice = Console.ReadLine();
// 通常你会在这里使用 switch 语句来处理选择
} while (choice != "4");
Console.WriteLine("Exiting program. Goodbye!");
}
}

这个循环将总是先显示一次菜单,然后在每次操作后继续显示,直到用户输入 ‘4’。

尝试一个可能失败的操作(例如网络连接),并在放弃前重试几次。

using System;
using System.Threading.Tasks;
class Program
{
// Random 实例应该只创建一次并重复使用
private static readonly Random _random = new Random();
static async Task Main()
{
bool isConnected = false;
int attempt = 0;
const int maxAttempts = 3;
do
{
attempt++;
Console.WriteLine($"Attempt {attempt}: Trying to connect to the server...");
// 模拟一个可能失败的网络操作
isConnected = (_random.Next(0, 2) == 1);
if (!isConnected && attempt < maxAttempts)
{
await Task.Delay(1000); // 等待 1 秒后重试
}
} while (!isConnected && attempt < maxAttempts);
if (isConnected)
{
Console.WriteLine("Connection successful!");
}
else
{
Console.WriteLine($"Failed to connect after {maxAttempts} attempts.");
}
}
}

你可以嵌套 do...while 循环,尽管它不如嵌套 for 循环常见。它对于一些场景很有用,例如一个简单的游戏,询问用户是否想再玩一次。

using System;
class Program
{
static void Main()
{
string playAgain;
do
{
Console.WriteLine("\nStarting a new round!");
// 游戏本身的内部循环(例如,猜数字)
int numberToGuess = new Random().Next(1, 11);
int guess;
do
{
Console.Write("Guess a number between 1 and 10: ");
int.TryParse(Console.ReadLine(), out guess);
} while (guess != numberToGuess);
Console.WriteLine("You guessed it!");
// 外部循环条件
Console.Write("Play again? (yes/no): ");
playAgain = Console.ReadLine().ToLower();
} while (playAgain == "yes");
Console.WriteLine("Thanks for playing!");
}
}
  • 无限循环:确保 while 条件中的变量在循环体内部得到更新。如果它从未改变,你的循环可能永远不会结束。
  • 忘记分号:do...while 循环是 C# 中少数几个需要在 while (condition); 行末尾加分号(;)的控制结构之一。忘记加分号是一个常见的语法错误。