我有一个简单的菜单方法,你用箭头键突出显示选项,然后按ENTER或T键离开。然而,当我在while循环中有两个条件时,它不工作。我需要帮助来理解原因。我希望程序在按ENTER或T时离开while循环。
我测试的东西:
- 仅使用其中一个条件即可正常工作。
- 调试和键得到正确的值(enter或t)取决于我按什么。
- 在每个条件下使用()
do
{
key = Console.ReadKey(true).Key;
switch (key)
{
case ConsoleKey.LeftArrow:
{
if (currentSelection - 1 >= optionsPerColumn)
currentSelection -= optionsPerColumn;
break;
}
case ConsoleKey.RightArrow:
{
if (currentSelection - 1 + optionsPerColumn < diceMenuOptions.Length)
currentSelection += optionsPerColumn;
else if (optionsPerColumn < diceMenuOptions.Length)
currentSelection = diceMenuOptions.Length;
break;
}
case ConsoleKey.T:
{
if (canCancel)
return -1;
break;
}
}
} while (key != ConsoleKey.Enter || key != ConsoleKey.T); //This is not working
Console.CursorVisible = true;
return currentSelection;
问题是您当前正在检查密钥是否不是enter
或T
。这将不起作用,因为enter
和T
是两个不同的键,因此两个条件中的一个将始终是true
。
你需要把它改成while (key != ConsoleKey.Enter && key != ConsoleKey.T);
您正在比较两个键以离开while。你只需要颠倒一下逻辑。试试这样做:
public static void Main()
{
ConsoleKeyInfo key;
do
{
key = Console.ReadKey(true);
} while (key != ConsoleKey.Enter && key != ConsoleKey.T);
}