有时需要在循环代码的处理上有更精细的控制

c#提供了4个命令
break      立即终止循环
continue 立即终止当前的循环(继续执行下一次循环)
goto       可以跳出循环,到已标记好的位置上(最好不要使用)
return     跳出循环及其包含的函数

break举例:
            int i=1;
            while (i <= 10)
            {
                if (i == 6)
                    break;      
                //break,退出循环,继续执行循环后面的第一行代码
                Console.WriteLine("{0}",i++);
             }

continue举例:          
             int i;
            for (i = 1; i <= 10;i++ )
            {
                if ((i % 2) == 0)        //当i%2=0时,就终止循环,所以只显示1.3.5.7.9
                    continue;             //contiue,仅终止当前循环,而不是整个循环。
                Console.WriteLine("{0}", i);
             }


goto 举例:
             int i=1;
            while (i<=10)
            {
                if(i==6)               //当i=6时,则执行goto,跳至
                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.");

相关文章:

  • 2021-07-05
  • 2022-12-23
  • 2022-12-23
  • 2021-08-31
  • 2021-11-30
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-01-12
  • 2021-09-03
相关资源
相似解决方案