2017-02-21 65 views
-4
 int VillainId = -1; 
     Console.Write("Enter VillainId: "); 
     while (!int.TryParse(Console.ReadLine(), out VillainId)) 
     { 
      Console.WriteLine("You need to enter a valid Villain Id!"); 
      Console.Write("Enter VillainId: "); 
     } 

有人能告訴我while(**this code here**){//rest of the code}內部的代碼是如何工作的。我瞭解它是否在{}內部,但它在條件和循環中,直到成功解析數字爲止。這是如何運作的 ?在while表達式語句中執行代碼

+1

如果int.TryParse成功解析從Console.ReadLine()獲取的字符串,則返回true。它前面的'!'意味着反轉bool,所以'while'在parens中執行代碼,並且如果'int.TryParse'返回false,'while'再次執行 - 並且一次又一次地執行,直到'int.TryParse'返回true。 –

+1

因此,如果我理解正確,如果它的錯誤,它在{}中的工作,然後再次檢查,並通過它,你的意思是它再次運行整個try.parse,如果成功了int並返回true? –

+1

這是正確的,每當它再次發生時,它會再次爲新輸入調用'Console.ReadLine()',並將其傳遞給'int.TryParse()',它嘗試解析新值等,直到解析是成功的,它打破了循環。 [do/while循環](https://msdn.microsoft.com/en-us/library/370s1zax.aspx?f=255&MSPPError=-2147217396)是編寫該代碼的另一種方式,並且可能更容易讓您頭轉過身來。 –

回答

3

int.TryParse返回true,如果它成功地解析它從Console.ReadLine()得到的字符串。在它前面的!意味着反轉由int.TryParse返回的布爾值,所以while執行parens中的代碼,並且如果int.TryParse返回false,則將該假轉換爲true,並且while再次執行 - 並且一次又一次,直到int.TryParse返回true。 「While while執行」意味着parens中的代碼首先執行,然後如果結果是true,while的主體也會執行。

這是另一種編寫相同代碼的方法。它不太緊湊,但可能更容易遵循:

int VillainId = -1; 
bool parseOK = false; 
do 
{ 
    Console.Write("Enter VillainId: "); 

    parseOK = int.TryParse(Console.ReadLine(), out VillainId); 

    if (!parseOK) 
    { 
     Console.WriteLine("You need to enter a valid Villain Id!"); 
    } 
} while (! parseOK); 
2

int.TryParse()返回true如果轉換成功和! (logical negation operator)反轉在他右側的boolean值(!true是等於false)。

while評估條件的每一個循環,所以,每一個無效的輸入在while()塊碼將被執行。

的流量,基本上是:

Console.Write("Enter VillainId: "); 
// asks to user input 

while (!int.TryParse(Console.ReadLine(), out VillainId)) 
// while the conversion is not successfull 
{ 
    Console.WriteLine("You need to enter a valid Villain Id!"); 
    Console.Write("Enter VillainId: "); 
    // asks for user to input valid data 
} 
+0

我明白,什麼讓我困惑的是while循環執行try.parse每次檢查條件? –

+0

@StoyanGrigorov運行代碼並找出你自己。 – Servy

+0

在閱讀Ed Plunkett的評論後,我明白了它的工作原理。感謝您的輸入:) –