一、C# goto語句
goto語句把控制交給由標記標識符命名的語句。
語法格式如下:
goto label;
......
label: ...在C#中,任何語句都可以被標記。語句標記后緊跟一個冒號,一個標記標識符。
常用的格式如下:
goto identifier; // 標簽
goto case constant-expression; // switch-case標簽
goto default; // switch語言中的默認標簽?identifier:位於當前體中的標簽、相同的詞法范圍或goto語言的封閉范圍。
?case constant-expression:將控制傳遞給特定的switch-case標簽。請閱讀C# switch語句。
?default:將控制傳遞給switch語言中的默認標簽。
二、提示
?goto語句還可以用於跳出深嵌套循環。
?goto語句只能在當前層內跳轉。
?要避免使用goto語句。
三、示例
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Test
{
class Program
{
static void Main(string[] args)
{
// C# goto語句-www.baike369.com
int x = 10;
Console.WriteLine("x = {0}", x);
if (x == 10)
{
x = 20;
goto A;
}
x = x + 1;
for (int i = 1; i <= 5; i++)
{
Console.WriteLine(i);
}
A: Console.WriteLine("x = {0}", x);
Console.ReadLine();
}
}
}
因為goto語句直接跳轉到了A:處,所以for語句沒有執行。
運行結果:
x = 10
x = 20