goto (C# 參考使用

來源:互聯網
上載者:User
goto (C# 參考)

goto 陳述式將程式控制直接轉移到標記陳述式。

 備註

goto 的常見用法是轉移控制至特定的 switch-case 標記或 switch 陳述式中預設的標記。

goto 陳述式對於跳出複雜的巢狀迴圈也很有用。

 範例

下列範例說明在 switch 陳述式中使用 goto

複製程式碼
// statements_goto_switch.csusing System;class SwitchTest{static void Main(){Console.WriteLine("Coffee sizes: 1=Small 2=Medium 3=Large");Console.Write("Please enter your selection: ");string s = Console.ReadLine();int n = int.Parse(s);int cost = 0;switch (n){case 1:cost += 25;break;case 2:cost += 25;goto case 1;case 3:cost += 50;goto case 1;default:Console.WriteLine("Invalid selection.");break;}if (cost != 0){Console.WriteLine("Please insert {0} cents.", cost);}Console.WriteLine("Thank you for your business.");}}
輸入
2
範例輸出
Coffee sizes: 1=Small 2=Medium 3=LargePlease enter your selection: 2Please insert 50 cents.Thank you for your business.

以下的範例說明使用 goto 以中斷巢狀迴圈。

複製程式碼
// statements_goto.cs// Nested search loopsusing System;public class GotoTest1{static void Main(){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.");}}
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.