如何让程序只接受指定的键,否则终止?

How to make a program accept only the specified key, and terminate otherwise?

我只是没有在 Microsoft 文档中找到它。我尝试在 Console.ReadKey(); 中使用括号内的参数,但它不起作用。

如果用户按下的键不是程序消息中指定的键,我需要让程序终止。例如,程序要求用户按下 Enter 键。如果用户决定按不同的键,我希望程序终止。

代码示例:

using System;

namespace ConsoleApp10
{
    class Program
    {
        static void Main(string[] args)
        {

            Console.WriteLine("Let's try to enter some number and show it in a console? (Press Enter/Return key to continue)");

            Console.ReadKey();

            Console.WriteLine("Enter your value");

            double x = Convert.ToDouble(Console.ReadLine());

            Console.WriteLine($"Your value is {x}");

            Console.WriteLine("Press any key to exit");

            Console.ReadKey();
        }
    }
}
var pressedKey = Console.ReadKey();
if (pressedKey.KeyChar != '\r')
{
    Environment.Exit(0);
}
else
{
    continue;
}

如果按下除 enter 以外的任何键,以上代码应退出控制台应用程序。

我找到了解决办法:

using System;

namespace ConsoleApp10
{
    class Program
    {
        static void Main(string[] args)
        {

            Console.WriteLine("Let's try to enter some number and show it in a console? (Press Enter/Return key to continue)");

            while (Console.ReadKey(true).Key != ConsoleKey.Enter);

            Console.WriteLine("Enter your value");

            double x = Convert.ToDouble(Console.ReadLine());

            Console.WriteLine($"Your value is {x}");

            Console.WriteLine("Press any key to exit");

            Console.ReadKey();
        }
    }
}

它没有做一些我需要的东西,但它也很糟糕

试试这个 -

Console.WriteLine("Let's try to enter some number and show it in a console? (Press Enter/Return key to continue)");

// exits if the key is not the Enter key
if (Console.ReadKey().Key != ConsoleKey.Enter)
    Environment.Exit(0);

Console.WriteLine("Enter your value");
double x = Convert.ToDouble(Console.ReadLine());
Console.WriteLine($"Your value is {x}");
Console.WriteLine("Press any key to exit");
Console.ReadKey();