我有一个非常大的循环,循环一个1000行。我退出循环,如果魔法值1被发现。如果没有找到魔法值1,但魔法值2被发现,则循环需要跳到开始。现在,我使用的是开关,一些如果和一个goto。我已阅读,goto语句是不是最好的方式。有没有更好的办法,使这项工作?

有帮助吗?

解决方案

要退出循环可以使用语句,去到下一个记录,你可以使用继续声明。

for(int i = 0; i < 1000; i++)
{
    if(magicValue1)
       break;
    if(magicValue2)
       continue;
}

<强>我不容忍goto语句我只是指出阿可能的使用情况的使用

您可以使用转到跳转语句来启动/退出循环,但是我会远离这个选项消失,除非你正在使用的嵌套循环。我认为goto语句仍然有它的优化,清洁ECT退出用途..但一般最好是使用它的相当谨慎。

for(int i = 0; i < 100; i++)
{ 
  start:

  for(int i = 0; i < 10; i++)
  {
     if(magicValue1)
       goto end;
    if(magicValue2)
       goto start;
  }
}
end : 

其他提示

这样如何:

for(int i = 0; i < 1000; i++) {
    if(values[i] == MAGIC_VALUE_1) {
        break;
    } else if(values[i] == MAGIC_VALUE_2) {
        i = 0;
    }
}

如果以“跳到开头”你的意思是“跳过此记录和处理的下一个”,与i = 0替换continue

没有whilebreak变化:

bool continue = true; int i = 0;
while (i < 1000 && continue){
    if(values[i] == MAGIC_VALUE_1) {
        continue=false;
    } else if(values[i] == MAGIC_VALUE_2) {
        i = 0;
    }
    i++;
}

我不能评论还(1个代表点的距离)

,但不会这是更好的:

for (int i = 0; i < 1000; i++)
{
    if (magicValue1)
    {
       break;
    }
    else if (magicValue2)
    {
       dosomething();
       i=0;
    }
}

和我不知道什么被用“重新搜索”的意思。

我要带#2的情况下意味着要不要执行(即跳过)循环体中的#2的情况下,而不是要在循环重置为0(见代码注释如果我已经得到了该向后。)

该建议可能的,因为在for循环不太常规条件是有争议的,可以说是低的自我记录的规模,但如果不打扰你,写一个简洁的方式是什么,我认为你你要的是:

        for (int i= 0; i<values.Length && values[i]!= MAGIC_1; i++)
        {
            if (values[i] == MAGIC_2)
            {
                // Don't do the loop body for this case but continue on looping
                continue;
                // If you want to reset the loop to zero instead of skip the 2 case,
                // comment-out the continue; and un-comment the line below:
                // i=0;
            }
            // Do long loop body here
        }

不过请注意,如果你设置的计数器回到0,如果MagicValue是2,和你的代码永远不变的价值观,你可能要在一个无限循环。

一个更复杂的可以是:

我们定义2种扩展方法。

public static class Extensions
{
   public static bool isMagic_1(this int i)
   {
         return i == 1;
   }

   public static bool isMagic_2(this int i)
   {
         return i == 2;
   }
}

现在,你可以这样做:

  for(int i = 0; i < 1000; i++)
  {
     if(i.isMagic_1())
       break;
     if(i.isMagic_2())
       continue;
  }

希望这有助于!

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top