while(C# 参考)while (C# Reference)

在指定的布尔表达式的计算结果为 true 时,while 语句会执行一条语句或一个语句块。The while statement executes a statement or a block of statements while a specified Boolean expression evaluates to true. 由于在每次执行循环之前都会计算此表达式,所以 while 循环会执行零次或多次。Because that expression is evaluated before each execution of the loop, a while loop executes zero or more times. 这不同于 do 循环,该循环执行一次或多次。This differs from the do loop, which executes one or more times.

while 语句块中的任何点,都可使用 break 语句中断循环。At any point within the while statement block, you can break out of the loop by using the break statement.

可通过使用 continue 语句直接步入 while 表达式的计算部分。You can step directly to the evaluation of the while expression by using the continue statement. 如果表达式计算结果为 true,则继续执行循环中的第一个语句。If the expression evaluates to true, execution continues at the first statement in the loop. 否则,将在循环后的第一个语句处继续执行。Otherwise, execution continues at the first statement after the loop.

还可以使用 gotoreturnthrow 语句退出 while 循环。You also can exit a while loop by the goto, return, or throw statements.

示例Example

下面的示例演示 while 语句的用法。The following example shows the usage of the while statement. 选择“运行”以运行示例代码 。Select Run to run the example code. 然后可以修改代码并再次运行它。After that you can modify the code and run it again.

int n = 0;
while (n < 5)
{
    Console.WriteLine(n);
    n++;
}

C# 语言规范C# language specification

有关详细信息,请参阅 C# 语言规范中的 while 语句部分。For more information, see The while statement section of the C# language specification.

请参阅See also