Skip to main content
 首页 » 编程设计

c#之两条件 While 循环,其中之一结束程序

2024年02月05日13langtianya

我有一些代码可以在用户键入“q”时退出程序

//press 'q' to quit application 
ConsoleKeyInfo info = Console.ReadKey(true); ; 
while (info.KeyChar != 'q') { 
    info = Console.ReadKey(true); 
} 

如果捕获的键是“p”,我该如何修改这个结构,以便有不同的非终止行为?

如果我将条件更改为:

(info.KeyChar != 'q') && (info.KeyChar != 'p') 

然后'p'也会终止程序。即使我将逻辑放在 while 循环中来处理“p”情况。

还有:

ConsoleKeyInfo info = Console.ReadKey(true); 
while (true) { 
    info = Console.ReadKey(true); 
    if (info.KeyChar == 'q') break; 
    else if (info.KeyChar == 'p') { 
        //other behavior 
     } 
} 

出于某种原因要求用户按“q”两次以结束程序,但预期的行为是通过一次按键触发操作。

请您参考如下方法:

var exitWhile = false; 
while (!exitWhile) { 
    ConsoleKeyInfo info = Console.ReadKey(true); 
    switch (info.KeyChar) { 
        case 'q': 
            exitWhile = true; 
            break; 
 
        case 'p': 
            //something else to do 
    } 
}