例如下例設計一個自動販賣機的程式,基本消費為 25 元,增量一次增加 10 元
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | class Demo { static void Main() { int n = 2; int cost = 0; switch (n) { case 1: cost += 25; break ; case 2: cost += 10; goto case 1; case 3: cost += 10; goto case 1; default : System.Console.WriteLine( "Are you sure?" ); break ; } System.Console.WriteLine( "Please insert NT${0}." , cost); } } /* 《程式語言教學誌》的範例程式 檔名:gotodemo1.cs 功能:示範 C# 程式 作者:張凱慶 時間:西元 2013 年 6 月 */ |
編譯執行,結果如下

下例示範跳出迴圈 (loop)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 | class Demo { static void Main() { int i = 0; while (i < 10) { if (i == 5) { goto Test; } if (i == 2) { goto Hello; } if (i == 8) { goto Spoon; } i++; } Test: System.Console.WriteLine( "The loop is breaked by goto." ); goto End; Hello: System.Console.WriteLine( "Hello world!" ); goto End; Spoon: System.Console.WriteLine( "There is no spoon." ); goto End; End: System.Console.WriteLine( "The end." ); } } /* 《程式語言教學誌》的範例程式 檔名:gotodemo2.cs 功能:示範 C# 程式 作者:張凱慶 時間:西元 2013 年 6 月 */ |
編譯執行,結果如下

中英文術語對照 | |
---|---|
關鍵字 | keyword |
迴圈 | loop |
您可以繼續參考
控制結構
相關目錄
回 C# 快速導覽
回 C# 教材
回首頁
參考資料
Standard ECMA-334 C# Language Specification
msdn: goto (C# 參考)
沒有留言:
張貼留言