6

我不明白我在这里缺少什么,但它似乎Console.ReadKey()仍然处于活动状态并且导致控制台让我Console.ReadLine()在调用后使用时输入两次Console.ReadKey()

一旦做出选择,我已经上下搜索了如何逃脱ReadKey(),但无济于事。

为了澄清,这是出乎意料的行为:当控制台弹出时,作为示例向用户呈现这三个选项。当用户随后键入“u”或“h”时,控制台不会等待;它会立即执行操作,而无需用户按下Enter

我做错了什么吗?

static void Main(string[] args)
{
    Console.WriteLine("u up");
    Console.WriteLine("h home");
    Console.WriteLine("x exit");
    Console.WriteLine("---------------------------------");
    Console.WriteLine("      [Enter Your Selection]");
    Console.WriteLine("---------------------------------");
    Console.Write("Enter Selection: ");
    ConsoleKeyInfo selection;
    Console.TreatControlCAsInput = true;
    int value;
    selection = Console.ReadKey();
    if (char.IsDigit(selection.KeyChar))
    {
        value = int.Parse(selection.KeyChar.ToString());
        value -= 1;
        Console.WriteLine("You've entered {0}", value);
    }
    else
    {
        switch (selection.Key)
        {
            case ConsoleKey.U:
                blurp();
                break;

            case ConsoleKey.H:
                blurp();
                break;

            case ConsoleKey.X:
                System.Environment.Exit(0);
                break;

            default:
                Console.WriteLine("Invalid Input...");
                break;
        }
    }
}

public static void blurp()
{
    Console.WriteLine("");
    Console.Write("Enter Another Value: ");
    string value = Console.ReadLine();
    Console.WriteLine("You've entered {0}", value);
}
4

3 回答 3

5

我用这段代码进行了测试并得到了相同的行为:

Console.Write("Enter Selection: ");
Console.TreatControlCAsInput = true;
ConsoleKeyInfo selection = Console.ReadKey();
if (selection.Key == ConsoleKey.U)
{
    Console.Write("Enter Another Value: ");
    string valueStr = Console.ReadLine();
    Console.WriteLine("You've entered {0}", valueStr);
}

解决方案是不使用Console.TreatControlCAsInput = true;,因为这会导致问题。

更多信息在 Stack Overflow 问题TreatControlCAsInput 问题中。这是一个错误吗?.

于 2017-02-20T20:14:08.383 回答
3

至于没有写出的控制台

 "You've entered ..."

发生这种情况是因为程序在离开方法并且控制台关闭时终止。要么在不调试 ( Ctrl+ F5) 的情况下运行它,要么在 main 的末尾添加一个 Console.ReadLine()。

由于 Console.ReadKey() 的工作方式,控制台不会在第一次输入后等待。如果您想等待用户按下Enter,请使用 ReadLine()。

至于 Console.ReadLine() 在存储输入之前等待两次,那是因为您正在使用

Console.TreatControlCAsInput = true;

这与控制台如何在内部接受输入相混淆。摆脱它。

于 2017-02-20T20:15:59.927 回答
3

问题在于设置:

Console.TreatControlCAsInput = true;

如果您将此行注释掉,一切都会按预期进行。这是 C# 中的已知功能。

如果还想设置 Console.TreatControlCAsInput = true; 您可以添加自定义方法来读取输入:

public static string CustomReadLine()
{
    ConsoleKeyInfo cki;
    string value = string.Empty;

    do
    {
        cki = Console.ReadKey();

        value = value + cki.Key;
    } while (cki.Key != ConsoleKey.Enter);

    return value;
}

更改您的代码

string value = Console.ReadLine();

使用此自定义功能

string value = CustomReadLine();

当你有 Console.TreatControlCAsInput = true; 时请参考 MSDN 文章Console.TreatControlCAsInput 属性来读取输入;

于 2017-02-20T20:50:51.393 回答