繁体   English   中英

C#中的goto语句

[英]goto statement in C#

我正在写一个像C#一样的函数:

public void CountNumber() 
{
       for(int i = 0; i < 40; i++) {
          if(i > 20) {
               goto out1;
          }

          Console.WriteLine("hello " + 1);

          out1:
             string hello = "";
       }
}

这基本上计算数字,如果i大于20,则不应写入console.writeline。 它应该跳过并点击“out1”但是“out1”最终需要有一个函数来编译。 它需要有“string hello =”“”来编译。 我不需要“string hello =”“”。 我只是希望它什么也不做,并且循环结束了。 如果没有out1:语句需要的“string hello =”“”,有没有办法做到这一点? 喜欢:

public void CountNumber() 
{
       for(int i = 0; i < 40; i++) {
          if(i > 20) {
               goto out1;
          }

          Console.WriteLine("hello " + 1);

          out1:
       }
}

谢谢。

尽管说使用goto有更好的方法来解决这个问题是绝对正确的,但我注意到没有人真正回答过你的问题。

标签必须标记声明 您想要转到没有与之关联的语句的位置。 您可以使用单个分号或空块创建空语句。

    out1:
    ;
} 

要么

    out1:
    {}
}

但就像他们说的那样,如果你能避免它,就不要去那里。

这个循环可以很容易地用很多其他方式编写 - 你可以在i<=20而不是i<40 (最好)的情况下循环,或者将Console.WriteLine调用移动到if语句中并使用if反转。

但是,我假设您正试图在“真实”案例中使用更精细的场景。 如果是这种情况,而不是使用goto ,只需使用continue跳过循环的其余部分:

public void CountNumber() 
{
   for(int i = 0; i < 40; i++) {
      if(i > 20) {
         continue; // Skips the rest of this loop iteration
      }

      Console.WriteLine("hello " + 1);
   }
}

类似地,如果在您的实际情况中更合适,您可以使用break来完全摆脱循环而不处理更多元素。

只是颠倒你的情况 - if...else可能是另一种选择。 我假设还有其他代码,否则你可以将for循环本身更改for最多20个。

   for(int i = 0; i < 40; i++) 
   {
      if(i <= 20) 
      {
          Console.WriteLine("hello " + 1);
      }
      //other code
   }

还有一些其他类似goto的语句,你应该考虑使用:

  • continue进入当前循环的下一次迭代。
  • break离开当前循环
  • return退出当前方法

如果以上都不符合您的要求,您应该只考虑goto 根据我的经验,这种情况很少发生。

看起来你想在这里continue使用。

您可以使用continue关键字:

public void CountNumber()  {
  for(int i = 0; i < 40; i++) {
    if(i > 20) {
      continue;
    }
    Console.WriteLine("hello " + 1);
  }
}

但是,请考虑使用if代替:

public void CountNumber()  {
  for(int i = 0; i < 40; i++) {
    if(i <= 20) {
      Console.WriteLine("hello " + 1);
    }
  }
}
public void CountNumber() 
{
       for(int i = 0; i < 40; i++) {
          if(i > 20) {
              continue;
          }

          Console.WriteLine("hello " + 1);

       }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM