如何检查是否使用 ConsoleKeyInfo 按下了 2 个可能的键中的任何一个?

How to check if any of 2 possible keys is pressed with ConsoleKeyInfo?

我在使用 ConsoleKeyInfo 时遇到了一个非常愚蠢的问题。我想检查是否使用小键盘或常规顶部数字键输入了“1”。

 ConsoleKeyInfo keyPressed;
 keyPressed = Console.ReadKey();
 if (keyPressed = ConsoleKey.D1 || keyPressed = ConsoleKey.NumPad1)
 { }

出于某种原因我不能使用“||”操作员。是否可以在 1 if 循环中以某种方式检查它而不使用 Console.ReadLine(); 并强制用户按 enter 键?

您必须 compare 使用 == 而不是 =。 否则,您正在尝试分配值。

并且您必须比较 ConsoleKeyInfoKey 属性,它包含 ConsoleKey 枚举。

所以你的 if 应该是这样的:

if (keyPressed.Key == ConsoleKey.D1 || keyPressed.Key == ConsoleKey.NumPad1)