2017-04-15 77 views
-1

讓我來重述一下我的問題。在這段代碼中如何避免「while(true)」?

請考慮下面的代碼:

while (true) 
{ 
    Console.Write("Please enter something "); 
    userInput = Console.ReadLine(); 
    if (string.IsNullOrEmpty(userInput)) 
    { 
     break; 
    } 
    collection.Add(userInput); 
} 

怎樣纔可以改變,以避免使用while (true)

+0

代碼的氣味是主觀的,標準太多選擇。你能否將這個問題重新定義爲可以得到客觀答案的東西? – hvd

+0

是的,我會這樣做的。 – menteith

回答

0

我寧願看到這樣的結構:

string userInput; 
bool again; 
do 
{ 
    Console.Write("Please enter something "); 
    userInput = Console.ReadLine(); 
    if (again = !string.IsNullOrEmpty(userInput)) 
     collection.Add(userInput); 
} while (again); 
+0

我想出了一個類似的解決方案,區別在於我沒有像你那樣使用變量('again')。當你在不同的代碼片段中使用相同的條件語句時,這是一個問題嗎? – menteith

+0

@menteith檢查一個布爾值是一個非常有效的操作,我認爲它給你想要達到的目標有明確的意圖。 – itsme86

1

你可以試試這個

do 
{ 
    Console.Write("Please enter something "); 
    userInput = Console.ReadLine(); 
    if (!string.IsNullOrEmpty(userInput)) 
    { 
     collection.Add(userInput); 
    } 
}while(!string.IsNullOrEmpty(userInput)); 
+3

這不符合OP的代碼。只要輸入爲空或空白,它就會繼續。只要輸入是* not * null或空白,OP的代碼就會繼續。 – hvd

+0

@ hvd就在這裏。 – menteith

+0

@menteith故事的士氣 - 不要試圖避免一個完美有效的構造,它易於閱讀,易於遵循,沒有人爲的「bool」變量或重複條件檢查的必要邏輯。 –

2

你有while (true)現在的原因是因爲你的循環體的初始部分不適合在循環條件。因此,您可以通過將其重構爲函數來避免while (true)

bool TryGetUserInput(out string userInput) { 
    Console.Write("Please enter something "); 
    userInput = Console.ReadLine(); 
    return !string.IsNullOrEmpty(userInput); 
} 

... 

string userInput; 
while (TryGetUserInput(out userInput)) 
    collection.Add(userInput); 
+0

這確實是最簡單的方法,以防萬一原始結構必須被避免。特別是使用C#7.0本地函數和'out var'。 –

0

前面已經提到,代碼味道是主觀的這是事實,但在這種情況下,有反對使用while(true)一個簡單的說法。

您錯過了在代碼中表達的機會。考慮:

while(true) 

這是什麼告訴你有關代碼?除了潛在的這個代碼將無限期地運行外,我們什麼也不知道。

現在考慮:

while(inputIsNotEmpty) 

我們立即知道行動塊或語句運行,直到輸入爲空。這將節省代碼讀者(主要是你自己)一些時間,而不必尋找退出條件。

這是我將如何避免在這種特殊情況下使用while(true)

do{ 
    Console.Write("Please enter something "); 
    input = Console.ReadLine(); 
    if (inputIsNotEmpty(input)) collection.Add(input); 
    } while (inputIsNotEmpty(input); 

... 

bool inputIsNotEmpty(string input) => !String.IsNullOrEmpty(input);