如何跳出循环

4

我在Main()函数中有一个while循环,它会调用多个方法。其中一个名为ScanChanges()的方法包含if/else语句,在if条件下,必须跳转到循环末尾的Thread.Sleep(10000)

static void Main(string[] args)
{    
    while (true)
    {
        ChangeFiles();    
        ScanChanges();    
        TrimFolder();    
        TrimFile();    
        Thread.Sleep(10000);
    }
}    

private static void ChangeFiles()
{
    // code here
}

private static void ScanChanges()
{
} 

FileInfo fi = new FileInfo("input.txt");
if (fi.Length > 0)
{
    // How to Escape loop??
}
else
{
    Process.Start("cmd.exe", @"/c test.exe -f input.txt > output.txt").WaitForExit();
}
4个回答

6
让ScanChanges返回一些值,指示您是否必须跳转到循环的末尾:
class Program
    {
        static void Main(string[] args)
        {

            while (true)
            {
                ChangeFiles();

                bool changes = ScanChanges();

                if (!changes) 
                {
                    TrimFolder();

                    TrimFile();
                }
                Thread.Sleep(10000);
            }
        }


private static void ChangeFiles()
{
  // code here
}

private static bool ScanChanges()
{
     FileInfo fi = new FileInfo("input.txt");
     if (fi.Length > 0)
     {
         return true;
     }
     else
     {
         Process.Start("cmd.exe", @"/c test.exe -f input.txt > output.txt").WaitForExit();

         return false;
      }      
}

3

ScanChanges 在达到那个 if 语句时返回一个 bool,然后在 while 循环中添加另一个 if 语句,如果 ScanChanges 返回 true,则跳过这两个过程。


0
使用 break 关键字来跳出循环。
if (fi.Length > 0)
{
    break;
}

同样适用于这个注释,你不能直接在另一个方法中使用 break - 使用 jonsca 的方法。 - KilZone

0

将ScanChanges的返回值制作出来,如果它将要打破循环,则可以是布尔值,返回true,否则返回false。

然后在主函数中设置打破循环的条件。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接