C#中break,continue,return,,goto,throw的区别(转)
生活随笔
收集整理的這篇文章主要介紹了
C#中break,continue,return,,goto,throw的区别(转)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
break?????
語句用于終止最近的封閉循環或它所在的switch?語句。?控制傳遞給終止語句后面的語句(如果有的話)。
/// <summary>/// break 示例/// 在此例中,條件語句包含一個應該從?1?計數到?100?的計數器/// 但?break?語句在計數達到?4?后終止循環。/// </summary>static void Main(){for (int i = 1; i <= 100; i++){if (i == 5){break;}Console.WriteLine(i);}}?
continue?
語句將控制權傳遞給它所在的封閉迭代語句的下一次迭代。
/// <summary>/// continue 示例/// 在此示例中,計數器最初是從 1 到 10 進行計數 // 但通過將 continue 語句與表達式 (i< 9) 一起使用/// 跳過了 continue 與 for 循環體末尾之間的語句。/// </summary>static void Main(){for (int i = 1; i <= 10; i++){if (i < 9){continue;}Console.WriteLine(i);}}?
goto??????
語句將程序控制直接傳遞給標記語句。goto的一個通常用法是將控制傳遞給特定的switch-case?標簽或switch?語句中的默認標簽。?goto語句還用于跳出深嵌套循環。
/// <summary>/// goto 示例/// 輸入 2 /// 示例輸出/// Coffee sizes: 1=Small 2=Medium 3=Large/// Please enter your selection: 2 /// Please insert 50 cents. /// Thank you for your business./// </summary>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.");}?
/// <summary>/// goto 示例2/// 下面的示例演示了使用 goto 跳出嵌套循環/// 輸入?44?示例輸出?/// Enter?the?number?to?search?for:?44/// The number 44 is found./// End of search./// </summary>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."); }?
return ??
語句終止它出現在其中的方法的執行并將控制返回給調用方法。它還可以返回一個可選值。如果方法為void?類型,則可以省略return?語句。
?
throw????
語句用于發出在程序執行期間出現反常情況(異常)的信號。通常throw語句與try-catch或try-finally?語句一起使用。當引發異常時,程序查找處理此異常的catch?語句。也可以用
throw?語句重新引發已捕獲的異常。
?
/// <summary>/// thow 示例/// </summary>static void Main(){string s = null;if (s == null){throw new ArgumentNullException();}Console.Write("The string s is null");// not executed }?
轉載于:https://www.cnblogs.com/zhizhuo-1991/p/5591662.html
總結
以上是生活随笔為你收集整理的C#中break,continue,return,,goto,throw的区别(转)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Scala初体验
- 下一篇: 多线程的单元测试工具 - GroboUt