do 運算子迭代程式碼塊,直到條件查詢等於 false。do-while 迴圈也可以通過 gotoreturnbreakthrow 語句中斷。

do 關鍵字的語法是:

做{ 程式碼塊; } while( condition );

例:

int i = 0;

do
{
    Console.WriteLine("Do is on loop number {0}.", i);
} while (i++ < 5);

輸出:

“在迴圈編號 1 上執行操作。”
Do on on number number
“Do is on loop number 3.”
“Do is on loop number 4.”
Do on on number 5

while 迴圈不同,do-while 迴圈是 Exit Controlled 。這意味著 do-while 迴圈將至少執行一次其語句,即使條件第一次失敗也是如此。

bool a = false;

do
{
    Console.WriteLine("This will be printed once, even if a is false.");
} while (a == true);