更新:2007 年 11 月
while 语句执行一个语句或语句块,直到指定的表达式计算为 false。
示例
C# | 复制代码 |
---|---|
class WhileTest { static void Main() { int n = 1; while (n < 6) { Console.WriteLine("Current value of n is {0}", n); n++; } } } /* Output: 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 */ |
C# | 复制代码 |
---|---|
class WhileTest2 { static void Main() { int n = 1; while (n++ < 6) { Console.WriteLine("Current value of n is {0}", n); } } } /* Output: 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 循环执行零次或更多次。这与执行一次或多次的
当
C# | 复制代码 |
---|---|
class WhileTest3 { 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 语句