break-----立即终止循环,继续执行循环后面的第一行代码
continue-----立即终止当前的循环(继续执行下一次循环)
goto-----可以跳出循环,到已标记好的位置上(如果希望代码易于阅读和理解,最好不要使用该命令)
return-----跳出循环及其包含的函数
示例:
int i = 1;
while (i <= 10)
{
if (i == 6)
break;
Console.WriteLine("{0}",i++);
}
Console.ReadKey();//输出1`5的数字,因为break命令在i==6时终止了循环
int i;
for (i = 1; i <= 10; i++)
{
if ((i % 2) == 0)
continue;
Console.WriteLine(i);
}
Console.ReadKey();//只要i除以2的余数是0,continue语句就终止当前的循环,所以只显示数字1,3,5,7,9
int i = 1;
while (i <= 10)
{
if (i == 6)
goto exitPoint;
Console.WriteLine("{0}",i++);
}
Console.WriteLine("This code will never be reached.");
exitPoint:
Console.WriteLine("This code is run when the loop is exited using goto.");
Console.ReadKey();//输出1`5的数字和This code is run when the loop is exited using goto.使用goto退出循环是合法的
的,但使用goto从外部进入循环是非法的
无限循环
永远不终止的循环,
while(true)
{
//code in loop
}
示例:
int i = 1;
while (i <= 10)
{
if ((i % 2) == 0)
continue;
Console.WriteLine("{0}",i++);
}
Console.ReadKey();
当i为2时,程序会用相同的i值进行下一个循环,然后测试这个i值,继续循环,一直这样下去,这就会冻结了应用程序.