2013-08-30 91 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"); 
}