如何在 C# 中的 while 迴圈中使用 continue 語句?


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

C# 中的 continue 語句的工作原理有點像 break 語句。然而,它不是強制終止,而是強制進行迴圈的下一輪迭代,跳過其中的任何程式碼。

對於 while 迴圈,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();
      }
   }
}

輸出

value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 16
value of a: 17
value of a: 18
value of a: 19

更新於:23-06-2020

172 次瀏覽

開啟您的 職業生涯

完成課程獲得認證

開始吧
廣告
© . All rights reserved.