我刚刚开始学习 C# 控制台事件。
有没有一种可能的方法,让 C# 应用程序只需按一个字母即可自动跳转到新命令。
我在下面有这个迷你代码。
我正在开发一个迷你文本库。
我刚刚使用了 Console.Read(); 所以用户输入字母 Y 然后他仍然需要按 Enter 键 我想要的是,如果用户按“y”或键盘上的任意键,则语句将转到 if 语句。
这可能吗?
Console.Write("Press Y to start the game.");
char theKey = (char) Console.Read();
if (theKey == 'y' || theKey == 'Y')
{
Console.Clear();
Console.Write("Hello");
Console.ReadKey();
}
else
Console.Write("Error");
最佳答案
您应该使用ReadKey
方法(msdn):
Console.Write("Press Y to start the game.");
char theKey = Console.ReadKey().KeyChar;
if (theKey == 'y' || theKey == 'Y')
{
Console.Clear();
Console.Write("Hello");
Console.ReadKey();
}
else
Console.Write("Error");
ReadKey
方法的返回值是ConsoleKey
枚举,因此您可以在if条件中使用它:
Console.Write("Press Y to start the game.");
ConsoleKey consoleKey = Console.ReadKey().Key;
if (consoleKey == ConsoleKey.Y)
{
Console.Clear();
Console.Write("Hello");
Console.ReadKey();
}
else
Console.Write("Error");
关于C# 控制台按键事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28655314/