首页 > 解决方案 > 如何在 if 语句中使用 Console.ReadLine()?

问题描述

static void DelayText(string text, int delay = 1000) {
    if (Console.ReadLine()) {
            Console.WriteLine(text);
        }
        else {
            System.Threading.Thread.Sleep(delay);
            Console.WriteLine(text);
        }
    }

我正在尝试创建一种自动接受文本输入并将其延迟一定量的方法,但是如果按下某个键,它只会立即写入文本。

我知道错误,以及为什么会发生

main.cs(83,15): error CS0029: Cannot implicitly convert type `string' to `bool'

但我似乎无法弄清楚如何做到这一点。

有任何想法吗?

标签: c#console

解决方案


您将在下面找到优化后的代码

static void DelayText(string text, int delay = 1000)
{
   if (string.IsNullOrEmpty(Console.ReadLine()))
       System.Threading.Thread.Sleep(delay);
   Console.WriteLine(text);
}

推荐阅读