2010-03-29 113 views
19

如何在C#中編寫Do .. While循環?做..在C#while循環嗎?

(編輯:!我是一個程序員VB.NET試圖使移動到C#,所以我確實有.NET/VB語法由於經驗)

+11

MSDN是這樣的問題的金礦。 C#'do'關鍵字:http://msdn.microsoft.com/en-us/library/370s1zax(VS.80).aspx – 2010-03-29 15:19:37

+0

既然你來自VB.NET,看看我提供的一些鏈接下面看循環的語法比較以及其他任何你需要在下面回覆 – dferraro 2010-03-29 15:43:56

回答

4
//remember, do loop will always execute at least once, a while loop may not execute at all 
//because the condition is at the top 
do 
{ 
    //statements to be repeated 
} while (condition); 
+0

你的條件不是布爾表達式... – 2010-03-29 15:15:58

+0

@Jon Skeet - 對不起,我通常是VB – BlackICE 2010-03-29 15:16:40

+1

do {} while(true ); – 2010-03-29 15:16:42

1

這裏有一個簡單的例子,將打印一些數字:

int i = 0; 

do { 
    Console.WriteLine(++i); 
} while (i < 10); 
42

的一般形式是:

do 
{ 
    // Body 
} while (condition); 

condition是一些表達鍵入bool

我個人很少編寫do/while循環 - for,foreach和直接while循環在我的經驗中更爲常見。後者是:

while (condition) 
{ 
    // body 
} 

whiledo...while之間的區別是,在第一種情況下,身體會永遠來,如果條件爲假開始與執行 - 而在後一種情況下,它總是執行一次前該條件被評估過。

+11

這就是關鍵。如果你想保證第一次執行,使用do-while。否則,雖然確實是一個更好的方法。 – 2010-03-29 15:21:08

1
using System; 

class MainClass 
{ 
    public static void Main() 
    { 
     int i = 0; 
     do 
     { 
      Console.WriteLine("Number is {0}", i); 
      i++; 
     } while (i < 100); 
    } 
} 

另一種方法是

using System; 

class MainClass 
{ 
    public static void Main() 
    { 
     int i = 0; 
     while(i <100) 
     { 
      Console.WriteLine("Number is {0}", i); 
      i++; 
     } 
    } 
} 
+0

感謝您的明確解釋 – 2010-03-29 16:57:50

0

除了安東尼Pegram的回答,您還可以使用while循環,它檢查條件之前進入循環

while (someCriteria) 
{ 
    if (someCondition) 
    { 
     someCriteria = false; 
     // or you can use break; 
    } 
    if (ignoreJustThisIteration) 
    { 
     continue; 
    } 
} 
1

相當令人驚訝的是,沒有人提到do..while結構的經典例子。做..當你想運行一些代碼,檢查或驗證某些東西(通常取決於執行代碼過程中發生的事情),並且如果你不喜歡結果,重新開始。這正是你需要什麼,當你想要一個適合一些限制某些用戶輸入:

bool CheckInput(string input) { ... } 
... 
string input; 
... 
do { 
    input=Console.ReadLine(); 
} while(!CheckInput(input)); 

這是一個相當通用的形式:當條件很簡單,這是常見的,直接把它放在循環結構(內部「while」關鍵字後的括號),而不是有一個方法來計算它。

這種用法的關鍵概念是,您必須至少請求一次用戶輸入(在最好的情況下,用戶將在第一次嘗試時就能正確使用)。並且在身體至少執行過一次之前,條件沒有多大意義。這些都是很好的提示,而且是工作的工具,它們兩者幾乎都是一種保證。

7

既然你提到你是來自VB.NET,我強烈建議檢出this link來顯示比較。您還可以使用this wensite將VB轉換爲C#,反之亦然 - 因此您可以使用現有的VB代碼,並查看它在C#中的外觀,包括循環和兒子下的其他任何東西。

要回答這個循環的問題,您簡單想要做的事,如:

while(condition) 
{ 
    DoSomething(); 
} 

你也可以做 - 而像這樣:

do 
{ 
    Something(); 
} 
while(condition); 

這裏的another code translator我已經成功使用,和another great C#->VB comparison website。祝你好運!

+0

感謝您的比較頁面的鏈接..這正是我需要的 – 2010-03-29 17:50:47