【问题标题】:C# - Use ReadKey for loopC# - 使用 ReadKey 进行循环
【发布时间】:2013-08-30 08:39:38
【问题描述】:
我已经在网上搜索了大约一个小时,但我找不到我的问题的答案。我对编程很陌生,我希望我不会浪费你的时间。如果单击“Y”,我希望我的程序循环,如果单击“N”则退出,如果单击任何其他按钮,则不执行任何操作。干杯!
Console.Write("Do you wan't to search again? (Y/N)?");
if (Console.ReadKey() = "y")
{
Console.Clear();
}
else if (Console.ReadKey() = "n")
{
break;
}
【问题讨论】:
标签:
c#
loops
while-loop
readkey
【解决方案2】:
这样你就错过了击键。存储 Readkey 的返回值,以便将其拆分。
此外,C# 中的比较使用 == 完成,char 常量使用单引号 (')。
ConsoleKeyInfo keyInfo = Console.ReadKey();
char key = keyInfo.KeyChar;
if (key == 'y')
{
Console.Clear();
}
else if (key == 'n')
{
break;
}
【解决方案3】:
您可以使用 keychar 来检查是否按下了字符
使用可以通过下面的例子来理解
Console.WriteLine("... Press escape, a, then control X");
// Call ReadKey method and store result in local variable.
// ... Then test the result for escape.
ConsoleKeyInfo info = Console.ReadKey();
if (info.Key == ConsoleKey.Escape)
{
Console.WriteLine("You pressed escape!");
}
// Call ReadKey again and test for the letter a.
info = Console.ReadKey();
if (info.KeyChar == 'a')
{
Console.WriteLine("You pressed a");
}
// Call ReadKey again and test for control-X.
// ... This implements a shortcut sequence.
info = Console.ReadKey();
if (info.Key == ConsoleKey.X &&
info.Modifiers == ConsoleModifiers.Control)
{
Console.WriteLine("You pressed control X");
}