跳轉語句用於改變程序的執行流程,轉移到指定之處。
C#中有4中跳轉語句:如下圖所示:
1.Break語句
可以使用Break語句終止當前的循環或者它所在的條件語句。然後,控制被傳遞到循環或條件語句的嵌入語句後面的代碼行。Break語句的語法極為簡單,它沒有括號和參數,只要將以下語句放到你希望跳出循環或條件語句的地方即可:
break;
Break語句例子
下面的代碼是一個Break語句的簡單例子:
[csharp]
<span style="font-family:KaiTi_GB2312;font-size:18px;">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
</span>
2.Continue 語句
若循環語句中有Continue關鍵字,則會使程序在某些情況下部分被執行,而另一部分不執行。在While循環語句中,在嵌入語句遇到Continue指令時,程序就會無條件地跳至循環的頂端測試條件,待條件滿足後再進入循環。而在Do循環語句中,在嵌入語句遇到Continue指令時,程序流程會無條件地跳至循環的底部測試條件,待條件滿足後再進入循環。這時在Continue語句後的程序段將不被執行。
Continue語句例子
例:輸出1-10這10個數之間的奇數。
[csharp]
<span style="font-family:KaiTi_GB2312;font-size:18px;">int i = 1;
while (i<= 10)
{
if (i % 2 == 0)
{
i++;
continue;
}
Console.Write (i.ToString()+”,”);
i++;
}
本程序的輸出結果為 1,3,5,7,9
</span>
3.Goto語句
Goto語句可以跳出循環,到達已經標識好的位置上。
一個Goto語句使用的小例子
例 : 使用Goto語句參與數據的查找。
程序代碼:
<span style="font-family:KaiTi_GB2312;font-size:18px;">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();
}
}
}
</span>
運行結果:
4.Return語句
Return語句是函數級的,遇到Return該方法必定返回,即終止不再執行它後面的代碼。
Return語句的一個例子
例 一個關於return跳轉語句的簡單例子。
程序代碼:
[csharp]
<span style="font-family:KaiTi_GB2312;font-size:18px;">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;
}
}
}
</span>
運行結果分析:
上述的代碼運行出錯,錯誤描述為:“檢測到無法訪問的代碼”,並且在Console.WriteLine("can'tbe reached");這句代碼中提示,這說明Return語句已經阻止了後面語句的運行。