如何使程序只接受指定的密钥,否则终止?



我只是在微软文档中没有找到这个。我试图在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外的任何键,上述代码应退出控制台应用程序。

试试这个-

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();

我找到了一个解决方案:

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();
}
}
}

它不做一些我需要的东西,但它也工作

最新更新