C#-循环使用ReadKey
本文关键字:ReadKey 循环 C#- | 更新日期: 2023-09-27 18:29:41
我在网上搜索了大约一个小时,就是找不到问题的答案。我对编程很陌生,希望不要浪费你的时间。如果我单击"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;
}
这里有一个Console.ReadKey方法的例子:
http://msdn.microsoft.com/en-us/library/471w8d85.aspx
//Get the key
var cki = Console.ReadKey();
if(cki.Key.ToString() == "y"){
//do Something
}else{
//do something
}
您通过这种方式错过了按键。存储Readkey的返回,以便您可以将其拆分
此外,C#中的比较是用==
完成的,char常量使用单引号('
)。
ConsoleKeyInfo keyInfo = Console.ReadKey();
char key = keyInfo.KeyChar;
if (key == 'y')
{
Console.Clear();
}
else if (key == 'n')
{
break;
}
您可以使用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");
}
推测由"什么都不做";您打算让用户尝试按下有效键,直到他们按下为止。当某些条件为真时,您可以使用do语句(也称为do-loop)来重复某些代码,例如:
var validKey = false;
var searchAgain = false;
do
{
Console.Write("Do you want to search again? (Y/N): ");
string key = Console.ReadKey().KeyChar.ToString().ToLower(System.Globalization.CultureInfo.InvariantCulture);
Console.WriteLine();
if (key == "y")
{
validKey = true;
searchAgain = true;
}
else if (key == "n")
{
validKey = true;
searchAgain = false;
}
else
{
Console.WriteLine("Please press the 'Y' key or the 'N' key.");
}
} while (!validKey);
// Now do something depending on the value of searchAgain.
我用了";而不是";在!validKey
中,因为这样读起来更好:在(用户尚未按下有效键)时执行{this code}。如果您认为使用while
循环可以更好地读取代码,那么您可能更喜欢使用它。
CCD_ 5比特是这样的;y";或";Y";被按下,它很有可能处理任何字母,即使是那些有意外大小写变化的字母;参见土耳其语国际化:点和无点字母";我"土耳其怎么了?以解释为什么对这种事情要小心是个好主意。