如何避免 C# while 和 do-while 循环中的代码重复?

Jac*_*ult 5 c# language-agnostic loops while-loop do-while

我在具有以下结构的 C# 方法中有一个循环。

do
{
     getUserInput();
     if (inputIsBad)
     {
          doSomethingElse();
     } 
} while (inputIsBad);
Run Code Online (Sandbox Code Playgroud)

或者,使用 while 循环:

getUserInput();
while (inputIsBad)
{
     doSomethingElse();
     getUserInput();
}
Run Code Online (Sandbox Code Playgroud)

但是这两种方法都使用了冗余代码:do-while 有一个 if 语句和 while 循环检查相同的条件;while 循环在循环之前和内部都调用 getUserInput()。

是否有一种简单的、非冗余的、非临时的方式来完成这些方法模式所做的事情,无论是一般情况下还是在 C# 中,只涉及编写每个基本组件一次?

use*_*740 2

假设getUserInput(..)可以转换为产生布尔值*的表达式..

while (getUserInput()
    && isBadInput()) {
  doSomethingElse();
}

// Prompts for user input, returns false on a user-abort (^C)
private bool getUserInput() { .. }
Run Code Online (Sandbox Code Playgroud)

其他变化(假定没有非本地状态)显示在注释中。

*简单地说,它始终可以编写为包装函数 - 请参阅C#7 中引入的局部函数。(还有其他方法可以达到相同的效果,其中一些我认为“太聪明了”。)

// local function
bool getUserInputAlwaysTrue() {
   getUserInput(); // assume void return
   return true;
}

while (getUserInputAlwaysTrue()
    && isBadInput()) {
  doSomethingElse();
}
Run Code Online (Sandbox Code Playgroud)

在某些情况下,这可以进一步推动逻辑。一般前提成立:getUserInput()总是在下一个之前调用isBadInput()

// local function or member method
// Prompt for user input, returning true on bad input.
bool getCheckedUserInput() {
   getUserInput(); // assume void return
   return isBadInput();
}

while (getCheckedUserInput()) {
  doSomethingElse();
}
Run Code Online (Sandbox Code Playgroud)