[英]Equivalent of Ruby “redo” in C#
是否有一種在C#中執行redo
工作的等效方法? 即返回循環的頂部並重新執行而不檢查條件或增加循環計數器。 謝謝。
for (int i = 0; i < 100; i++)
{
do
{
DoYourStuff();
} while (ShouldWeDoThatAgain());
}
Do...while
就像一個標准的while
循環,除了不是在每次迭代之前檢查它的條件,它檢查之后。 這樣,循環內的代碼將始終至少執行一次。 堅持在for
或foreach
循環中,這應該得到你想要的行為。 這比Simon的回答簡單一點,因為它不需要額外的變量,不使用continue
,並且根本不會弄亂循環計數器。
為什么不簡單:
雖然goto
並不是每個人都喜歡的,但在這種情況下它很可讀......
for(...)
{
redo:
//...
if (...)
goto redo;
}
不,你最接近的是這樣的:
bool redoCalled = false:
for (int i = 0; i < 10; i++) {
if (redoCalled) {
i--;
redoCalled = false;
}
// other stuff here
if (redoWanted) {
redoCalled = true;
continue;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.