2013-08-30 85 views
0

我一直在网上搜索大约一个小时,而我找不到我的问题的答案。我对编程非常陌生,我希望我不会浪费你的时间。如果点击“Y”,我希望程序循环,如果点击“N”则退出,如果点击其他任何按钮,则不执行任何操作。干杯!C# - 使用ReadKey for循环

Console.Write("Do you wan't to search again? (Y/N)?"); 
if (Console.ReadKey() = "y") 
{ 
    Console.Clear(); 
} 
else if (Console.ReadKey() = "n") 
{ 
    break; 
} 
+0

那么这是什么现在怎么办?它不是做什么的? – Arran

回答

2

你缺少的击键这种方式。存储Readkey的返回值,以便将其分开。
此外,C#中的比较是使用==完成的,char常量使用单引号(')。

ConsoleKeyInfo keyInfo = Console.ReadKey(); 
char key = keyInfo.KeyChar; 

if (key == 'y') 
{ 
    Console.Clear(); 
} 
else if (key == 'n') 
{ 
    break; 
} 
1

可以使用作为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"); 
}