Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/sorting/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# “怎么可能?”;while(true)“;在这段代码中可以避免吗?_C# - Fatal编程技术网

C# “怎么可能?”;while(true)“;在这段代码中可以避免吗?

C# “怎么可能?”;while(true)“;在这段代码中可以避免吗?,c#,C#,让我重新表述我的问题 请考虑以下代码: while (true) { Console.Write("Please enter something "); userInput = Console.ReadLine(); if (string.IsNullOrEmpty(userInput)) { break; } collection.Add(userInput); } 如何更改它以避免使用,而(true)?您可以尝试此方法 do

让我重新表述我的问题

请考虑以下代码:

while (true)
{
    Console.Write("Please enter something ");
    userInput = Console.ReadLine();
    if (string.IsNullOrEmpty(userInput))
    {
        break;
    }
    collection.Add(userInput);
}
如何更改它以避免使用
,而(true)

您可以尝试此方法

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

我宁愿看到这个结构:

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

现在之所以有
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);

已经提到,代码气味是主观的,这是正确的,但在这种情况下,有一个简单的论点反对使用
而(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);

这与OP的代码的行为不同。只要输入为null或空,它就会继续。只要输入不为null或空,OP的代码就会继续运行。@hvd就在这里。@menteith故事的精神-不要试图避免一个完全有效的结构,它易于阅读,易于遵循,并执行必要的逻辑,不需要人工
bool
变量或重复条件检查。@IvanStoev这是一个很好的建议!作为一个新手,我经常会反复检查我的代码是否足够好,即使是在我的帖子中描述的简单的事情上。所以,清晰是第一位的。@hvd谢谢,我错过了一个!在代码内部,代码的味道是主观的,标准太多,无法选择。你能把这个问题重新表述成一个能得到客观答案的问题吗?是的,我会这样做。我提出了一个类似的解决方案,不同的是我没有像你那样使用变量(
)。在不同的代码段中使用相同的条件语句是否有问题?@menteith检查布尔值是一种非常有效的操作,我认为它清楚地说明了您要实现的目标。如果必须避免原始构造,这确实是最干净的方法。特别是使用C#7.0本地函数和
out var