while 语句执行一个语句或语句块,直到指定的表达式计算为 false。
示例
复制代码 | |
|---|---|
// statements_while.cs
using System;
class WhileTest
{
static void Main()
{
int n = 1;
while (n < 6)
{
Console.WriteLine("Current value of n is {0}", n);
n++;
}
}
} | |
输出
Current value of n is 1 Current value of n is 2 Current value of n is 3 Current value of n is 4 Current value of n is 5 | |
复制代码 | |
|---|---|
// statements_while_2.cs
using System;
class WhileTest
{
static void Main()
{
int n = 1;
while (n++ < 6)
{
Console.WriteLine("Current value of n is {0}", n);
}
}
} | |
输出
Current value of n is 2 Current value of n is 3 Current value of n is 4 Current value of n is 5 Current value of n is 6 | |
由于 while 表达式的测试在每次执行循环前发生,因此 while 循环执行零次或更多次。这与执行一次或多次的 do 循环不同。
当 break、goto、return 或 throw 语句将控制权转移到 while 循环之外时,可以终止该循环。若要将控制权传递给下一次迭代但不退出循环,请使用 continue 语句。请注意,在上面三个示例中,根据 int n 递增的位置的不同,输出也不同。在下面的示例中不生成输出。
复制代码 | |
|---|---|
// statements_while_3.cs
// no output is generated
using System;
class WhileTest
{
static void Main()
{
int n = 5;
while (++n < 6)
{
Console.WriteLine("Current value of n is {0}", n);
}
}
} | |
C# 语言规范
有关更多信息,请参见 C# 语言规范中的以下各章节:
-
5.3.3.7 While 语句
-
8.8.1 while 语句
请参见