我做了一个开关案例,我使用向上箭头键,向下箭头键并输入键。但是我无法想到如何将代码放入我可以选择选项的输入案例中。
public static void entries()
{
keyPressed = Console.ReadKey(true);
switch (keyPressed.Key)
{
case ConsoleKey.DownArrow:
if (keyPressed.Key.ToString() == "DownArrow")// selects the curitem when the down arrow key is pressed
{
curItem++;
if (curItem > menuItems.Length - 1) curItem = 0;
}
break;
case ConsoleKey.UpArrow:
if (keyPressed.Key.ToString() == "UpArrow")// selects the curitem when the up arrow key is pressed
{
curItem--;
if (curItem < 0) curItem = Convert.ToInt16(menuItems.Length - 1);
}
break;
case ConsoleKey.Enter:
if (keyPressed.Key.ToString() == "Enter")// when enter is pressed it will go to one of the choices
{
}
break;
default:
break;
}
}
答案 0 :(得分:1)
关于嵌套if
语句的想法是正确的,还是有另一个开关。我可能会将此重新考虑到另一个函数中:
case ConsoleKey.Enter:
chooseOption(curItem);
break;
...
void chooseOption(int item)
{
switch(item)
{
case 1:
//Do item 1
break;
case 2:
//Do item 2
break;
case 3:
//Do item 3
break;
}
}
答案 1 :(得分:0)
根据您的评论。以下是如何在menuItems数组中显示当前项目。我假设menuItems包含一些字符串或整数或者可以轻松写入控制台的东西。
case ConsoleKey.Enter:
// when enter is pressed it will go to one of the choices
Console.Clear();
Console.WriteLine(menuItems[curItem]);
break;