C# 中 break 和 continue 語句有什麼區別?


break 語句終止迴圈並將執行轉移到緊跟在迴圈後的語句。

continue 語句導致迴圈跳過其主體剩餘部分,並在迭代之前立即重新測試其條件。

如果在迴圈中遇到 break 語句,則會立即終止迴圈,並且程式控制元件從迴圈後的下一條語句恢復。

C# 中的 continue 語句的工作原理有點像 break 語句。然而,continue 並非強制終止,而是強制迴圈的下一次迭代進行,跳過其間的所有程式碼。

以下是 while 迴圈中使用 continue 語句的完整程式碼 −

示例

using System;
namespace Demo {
   class Program {
      static void Main(string[] args) {

         /* local variable definition */
         int a = 10;

         /* loop execution */
         while (a > 20) {
            if (a == 15) {
               /* skip the iteration */
               a = a + 1;
               continue;
            }
            Console.WriteLine("value of a: {0}", a);
            a++;
         }
         Console.ReadLine();
      }
   }
}

以下是 break 語句的一個示例 −

示例

using System;
namespace Demo {
   class Program {
      static void Main(string[] args) {
         /* local variable definition */
         int a = 10;

         /* while loop execution */
         while (a < 20) {
            Console.WriteLine("value of a: {0}", a);
            a++;

            if (a > 15) {
               /* terminate the loop using break statement */
               break;
            }
         }
         Console.ReadLine();
      }
   }
}

更新日期:2020 年 6 月 22 日

2K+ 瀏覽量

開啟你的 職業生涯

完成課程,獲得認證

開始
廣告