我在尝试找出如何跳出一个包含switch语句的循环时遇到了问题。break语句只能跳出switch语句,而不能跳出整个循环。
可能有更优雅的解决方案。我已经实现了一个标志(flag),它一开始为true,当被设置为false时结束循环。你能提供更好的解决方案吗?
背景:这段代码用于条形码工作流系统中。我们有内置条形码扫描仪的PocketPC。该代码用于其中一个功能。在整个过程中,它提示用户输入不同的数据。这部分允许他们在PocketPC终端上滚动查看一些库存记录(分页结果),并允许他们键入"D"表示完成,"Q"表示退出。
这是需要改进的C#示例:
```csharp while (true) { switch (action) { case "D": done = true; break;
case "Q": quit = true; break;
// Code to handle other cases...
default: break; }
if (done || quit) { break; } } ```
do
{
switch (MLTWatcherTCPIP.Get().ToUpper())
{
case "": //scroll/display next inventory location
MLTWatcherTCPIP.TerminalPrompt.ScrollBodyTextDown();
break;
case "P": //scroll/display previous inventory location
MLTWatcherTCPIP.TerminalPrompt.ScrollBodyTextDown();
break;
case "D": //DONE (exit out of this Do Loop)
// break; // this breaks out of the switch, not the loop
// return; // this exists entire method; not what I'm after
keepOnLooping = false;
break;
case "Q": //QUIT (exit out to main menu)
return;
default:
break;
}
} while (keepOnLooping);
以下是 VB.NET 实现该功能的示例代码:
Do
Select Case MLTWatcherTCPIP.Get().ToUpper
Case "" ''#scroll/display next inventory location
MLTWatcherTCPIP.TerminalPrompt.ScrollBodyTextDown()
Case "P" ''#scroll/display previous inventory location
MLTWatcherTCPIP.TerminalPrompt.ScrollBodyTextUp()
Case "D" ''#DONE (exit out of this Do Loop)
Exit Do
Case "Q" ''#QUIT (exit out to main menu)
Return
End Select
Loop
谢谢。