如何在C#中转义while循环

Jam*_*mes 58 .net c# windows

我试图逃避一个循环.基本上,如果满足"if"条件,我希望能够退出此循环:

private void CheckLog()
{
    while (true)
    {
        Thread.Sleep(5000);
        if (!System.IO.File.Exists("Command.bat"))
            continue;

        using (System.IO.StreamReader sr = System.IO.File.OpenText("Command.bat"))
        {
            string s = "";
            while ((s = sr.ReadLine()) != null)
            {
                if (s.Contains("mp4:production/CATCHUP/"))
                {
                    RemoveEXELog();

                    Process p = new Process();
                    p.StartInfo.WorkingDirectory = "dump";
                    p.StartInfo.FileName = "test.exe";
                    p.StartInfo.Arguments = s;
                    p.Start();

                    << Escape here - if the "if" condition is met, escape the loop here >>
                }
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Dir*_*irk 72

使用break;逃脱第一循环:

if (s.Contains("mp4:production/CATCHUP/"))
{
   RemoveEXELog();
   Process p = new Process();
   p.StartInfo.WorkingDirectory = "dump";
   p.StartInfo.FileName = "test.exe"; 
   p.StartInfo.Arguments = s; 
   p.Start();
   break;
}
Run Code Online (Sandbox Code Playgroud)

如果你想要转义第二个循环,你可能需要使用一个标志并检查out循环的守卫:

        boolean breakFlag = false;
        while (!breakFlag)
        {
            Thread.Sleep(5000);
            if (!System.IO.File.Exists("Command.bat")) continue;
            using (System.IO.StreamReader sr = System.IO.File.OpenText("Command.bat"))
            {
                string s = "";
                while ((s = sr.ReadLine()) != null)
                {
                    if (s.Contains("mp4:production/CATCHUP/"))
                    {

                        RemoveEXELog();

                        Process p = new Process();
                        p.StartInfo.WorkingDirectory = "dump";
                        p.StartInfo.FileName = "test.exe"; 
                        p.StartInfo.Arguments = s; 
                        p.Start();

                        breakFlag = true;
                        break;
                    }
                }
            }
Run Code Online (Sandbox Code Playgroud)

或者,如果您只想从嵌套循环中完全退出函数,请输入return;而不是a break;.

但这些并不是最佳实践.您应该找到一些方法将必要的布尔逻辑添加到您的while警卫中.


zel*_*lio 9

break 要么 goto

while ( true ) {
  if ( conditional ) {
    break;
  }
  if ( other conditional ) {
    goto EndWhile;
  }
}
EndWhile:
Run Code Online (Sandbox Code Playgroud)

  • "Goto"是一个令人敬畏的东西. (9认同)
  • @Dementic - 并非在所有情况下.如果巧妙地使用它,它可以提高可读性,可以帮助退出深度嵌套的循环,将控制转移到特定的开关案例标签等.如上面的示例zellio所示,它有助于退出而不使用任何其他变量等.来自https: //msdn.microsoft.com/en-us/library/13940fs2(v=vs.71).aspx"goto的一个常见用途是将控制转移到特定的switch-case标签或switch语句中的默认标签. goto语句对于摆脱深层嵌套循环也很有用." (3认同)
  • 当我们在'while'循环中使用'switch'关键字时它不起作用,所以只需添加另一个测试条件,例如bool bTurnOff = false; while(true && bTurnOff == false){...} (2认同)