跳转语句用于改变程序的执行流程,转移到指定之处。
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))
{
goto Found;
}
}
}
Console.WriteLine("The number {0} was not found.", myNumber);
goto Finish;
Found:
Console.WriteLine("The number {0} is found.", myNumber);
Finish:
Console.WriteLine("End of search.");
Console.ReadLine();
}
}
}
运行结果:

4.Return语句
Return语句是函数级的,遇到Return该方法必定返回,即终止不再执行它后面的代码。
Return语句的一个例子
例 一个关于return跳转语句的简单例子。
程序代码:
using System;
using System.Collections.Generic;
using System.Text;
namespace returnExample
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(Add(1, 2));
return;
Console.WriteLine("can't be reached");
}
static int Add(int a, int b)
{
return a + b;
}
}
}
运行结果分析:
上述的代码运行出错,错误描述为:“检测到无法访问的代码”,并且在Console.WriteLine("can'tbe reached");这句代码中提示,这说明Return语句已经阻止了后面语句的运行。
以上三篇博客是我总结的有关“C#控制流程”知识点,里面有定义解析、语法、实例、以及用到的有关知识点,非常详尽。具体详情请见博客链接。