C# do while循环设置两个或退出条件时无法正常跳出问题求助
问题根源
你遇到的是典型的逻辑运算符使用错误:
原循环条件 while (key != ConsoleKey.Enter || key != ConsoleKey.T) 是永真式,永远不会触发退出。
逻辑或||的规则是只要任意一个条件成立,整体结果就为真。而同一个key变量的值不可能同时等于Enter和T,所以不管你按什么键:
- 按Enter:
key != T成立,整体条件为真,循环继续 - 按T:
key != Enter成立,整体条件为真,循环继续 - 按其他键:两个条件都成立,循环继续
修正方案
把逻辑或||替换为逻辑与&&即可,逻辑与&&要求两个条件同时成立时整体结果才为真,也就是「当按键既不是Enter也不是T时,才继续循环」,符合你的需求。
你也可以用更符合直观表述的写法:!(key == ConsoleKey.Enter || key == ConsoleKey.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; } } // 两种写法二选一即可 // 写法1:逻辑与 } while (key != ConsoleKey.Enter && key != ConsoleKey.T); // 写法2:直观否定式 // } while (!(key == ConsoleKey.Enter || key == ConsoleKey.T)); Console.CursorVisible = true; return currentSelection;
额外注意点
你代码中T键的分支里加了canCancel的判断,如果canCancel为false,按T不会提前返回,这时候会走到循环条件判断,修正后的条件此时会正常触发退出。如果你的需求是只有canCancel为true时按T才能退出,那当前逻辑是符合要求的。
内容的提问来源于stack exchange,提问作者Laserlaxen
相关产品推荐
相关产品推荐

