ReadKey等待输入两次后的C#Console.ReadLine

Aut*_*mic 6 c# console console.readkey console.readline

我不明白我在这里缺少什么,但它似乎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);
}
Run Code Online (Sandbox Code Playgroud)

Tat*_*ved 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);
}
Run Code Online (Sandbox Code Playgroud)

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

更多信息,请参阅 Stack Overflow问题TreatControlCAsInput问题.这是一个错误吗?.