我有一个小的C#控制台应用程序我正在编写。
我希望应用程序等待用户关于Y或N键的指令(如果按下任何其他键,应用程序将忽略这一点,并等待Y或N,然后根据Y或N答案运行代码。
我想出了这个主意,
while (true)
{
ConsoleKeyInfo result = Console.ReadKey();
if ((result.KeyChar == "Y") || (result.KeyChar == "y"))
{
Console.WriteLine("I'll now do stuff.");
break;
}
else if ((result.KeyChar == "N") || (result.KeyChar == "n"))
{
Console.WriteLine("I wont do anything");
break;
}
}遗憾的是,VS说它不像result.Keychat ==,因为操作数不能应用于'char‘或'string’
有什么需要帮忙的吗?
提前谢谢。
发布于 2011-10-28 23:12:17
KeyChar是一个char,而"Y"是一个string。
您想要的是像KeyChar == 'Y'这样的东西。
发布于 2011-10-28 23:13:22
请检查这个
string result = Console.ReadLine();并在检查结果之后
发布于 2013-12-04 00:55:37
你要找的东西是这样的:
void PlayAgain()
{
Console.WriteLine("Would you like to play again? Y/N: ");
string result = Console.ReadLine();
if (result.Equals("y", StringComparison.OrdinalIgnoreCase) || result.Equals("yes", StringComparison.OrdinalIgnoreCase))
{
Start();
}
else
{
Console.WriteLine("Thank you for playing.");
Console.ReadKey();
}
}https://stackoverflow.com/questions/7931167
复制相似问题