C# 控制台中的智能用户输入处理
我必须: 1.向用户写入信息。 2.阅读输入的信息。 3.若消息为空,则关闭应用程序 通过以下方式读取用户输入并对其进行处理非常简单:C# 控制台中的智能用户输入处理,c#,console,C#,Console,我必须: 1.向用户写入信息。 2.阅读输入的信息。 3.若消息为空,则关闭应用程序 通过以下方式读取用户输入并对其进行处理非常简单: static void Main(string[] args) { string line; Console.WriteLine(message); while ((line = Console.ReadLine()).Length > 0) { //
static void Main(string[] args)
{
string line;
Console.WriteLine(message);
while ((line = Console.ReadLine()).Length > 0)
{
// process line here and return output to console
Console.WriteLine(message);
}
}
但由于我是一个纯粹主义者,我想省略所有重复的语句(如本例中的“Console.WriteLine(message);”)。我已经尝试过do{..}while(..)循环,但没有成功(重复了Console.ReadLine()语句)
您对如何完成此任务有什么聪明的想法吗?创建延迟计算的
IEnumerable
(假设我可以从下面示例中的方法ReadAllLines
获取此IEnumerable
),它将返回从控制台读取的行。然后,您可以使用LINQ执行以下操作:
while (true)
{
Console.WriteLine(message);
var line = Console.ReadLine();
if (line == "") break;
else DoStuff();
}
var lines = ReadAllLines()
.TakeWhile(line => line != "");
foreach (var line in lines) DoStuff();
使用无限循环和中断可以吗?我被告知这是“不受欢迎的编码”。在我看来,这没什么,因为C#没有任何更适合的结构。我更喜欢
while(true)
,而不是将一些移动到条件,从而复制它。我觉得这个话题很主观。