日期:2014-05-17  浏览次数:20778 次

C#中的主要流程控制语句之跳转语句


跳转语句用于改变程序的执行流程,转移到指定之处。

C#中有4中跳转语句:如下图所示:




1.Break语句

可以使用Break语句终止当前的循环或者它所在的条件语句。然后,控制被传递到循环或条件语句的嵌入语句后面的代码行。Break语句的语法极为简单,它没有括号和参数,只要将以下语句放到你希望跳出循环或条件语句的地方即可:

 break;

Break语句例子

下面的代码是一个Break语句的简单例子:

int i = 9;
while (i < 10)
    {
         if (i >= 0)
           { Console.WriteLine("{0}", i);
                  i--;
           }
          else 
           {
               break;
            }
      } 
运行结果:9、8、7、6、5、4、3、2、1、0 



2.Continue 语句


若循环语句中有Continue关键字,则会使程序在某些情况下部分被执行,而另一部分不执行。在While循环语句中,在嵌入语句遇到Continue指令时,程序就会无条件地跳至循环的顶端测试条件,待条件满足后再进入循环。而在Do循环语句中,在嵌入语句遇到Continue指令时,程序流程会无条件地跳至循环的底部测试条件,待条件满足后再进入循环。这时在Continue语句后的程序段将不被执行。

Continue语句例子

例:输出1-10这10个数之间的奇数。

int i = 1;
    while (i<= 10)
    {
       if (i % 2 == 0)
        {
          i++;
          continue;
        }
        Console.Write (i.ToString()+”,”);
        i++;
   }
 本程序的输出结果为 1,3,5,7,9


3.Goto语句


Goto语句可以跳出循环,到达已经标识好的位置上。

一个Goto语句使用的小例子

例 : 使用Goto语句参与数据的查找。

程序代码:

using System;
using System.Collections.Generic;
using System.Text;
namespace gotoExample
{
    class Program
    {
        static void Main(string[] args)
        {
            int x = 200, y = 4;
            int count = 0;
            string[,] array = new string[x, y];
            // Initialize the array:
            for (int i = 0; i < x; i++)
                for (int j = 0; j < y; j++)
                    array[i, j] = (++count).ToString();
            // Read input:
    Console.Write("Enter the number to search for: ");
            // Input a string:
            string myNumber = Console.ReadLine();
            // Search:
            for (int i = 0; i < x; i++)
            {
                for (int j = 0; j < y; j++)
                {
                    if (array[i, j].Equals(myNumber))