Console.ReadKey正在退出之前处理最后一项

Ani*_*esh 0 c# console-application

我有一个很小的命令行实用程序,它读取用户输入并将所有输入添加到列表中.Esc按下该键后,程序退出.但是,按下该Esc键后,即使Escape键也被添加到列表中,然后程序退出.

如何防止将Esc密钥添加到列表中?

码:

    ConsoleKeyInfo cki;
    List<string> stuffs = new List<string>();

    Console.WriteLine("Press Escape (Esc) to quit the program.");

    do {
        cki = Console.ReadKey();
        stuffs.Add(cki.Key.ToString());
        Console.WriteLine();
    } while(cki.Key != ConsoleKey.Escape);

    Console.WriteLine("You have entered the following data:");

    foreach(string stuff in stuffs)
        Console.WriteLine(stuff);
Run Code Online (Sandbox Code Playgroud)

Ree*_*sey 5

更改循环,以便在将值添加到列表之前检查该值.例如,这会循环相同,但在按下Escape时会中断:

while(true)
{
    cki = Console.ReadKey();
    if (cki.Key == ConsoleKey.Escape)
       break;

    stuffs.Add(cki.Key.ToString());
    Console.WriteLine();
}
Run Code Online (Sandbox Code Playgroud)