百科问答小站 logo
百科问答小站 font logo



c#有没有简洁的方法跳出外层循环,类似Java那样使用标记的方式? 第1页

  

user avatar   rednaxelafx 网友的相关建议: 
       Let me google that for you

看搜索结果里头几个爆栈站的回答就够了。

简单来说C#没有Java能给循环打label的语法,所以没有直接对应的办法。

解决方案有三个流派:

  1. goto派:直接在外层循环后面放个label,在内层循环里需要跳出外层循环时用goto到那个label。要知道Java的labeled break本质上就是用于这个用途的受限版goto,用在这里再合适不过了。 <- 我是这个流派的。
  2. flag派:在外层循环前声明个bool flag,然后在内层循环结束后检查一下该flag有没有说要跳出循环:
    bool flag = false; for (...) {   for (...) {     if (...) {       flag = true;       break;     }   }   if (flag) break; }
    这大概是所谓“正统派”。
  3. 把内层循环封装成一个返回bool的方法,外层循环调用这个方法看返回值决定要不要break。

还有更变态的用抛/接异常来做的…滥用异常实现控制流派。这是异端,好孩子不要学,所以不列在“三个流派”中。不过我们也不能教条的批判它,也得看看它有趣的一面,例如:

Unchecked Exceptions Can Be Strictly More Powerful Than Call/CC
goto (C# Reference)

- MSDN

The goto statement transfers the program control directly to a labeled statement.

A common use of goto is to transfer control to a specific switch-case label or the default label in a switch statement.

The goto statement is also useful to get out of deeply nested loops.

C#规范说:

A label can be referenced from goto statements within the scope of the label. [Note: This means that goto statements can transfer control within blocks and out of blocks, but never into blocks. end note]

The target of a goto identifier statement is the labeled statement with the given label. If a label with the given name does not exist in the current function member, or if the goto statement is not within the scope of the label, a compile-time error occurs. [Note: This rule permits the use of a goto statement to transfer control out of a nested scope, but not into a nested scope. In the example
using System; class Test {   static void Main(string[] args) {     string[,] table = {       {"red", "blue", "green"},       {"Monday", "Wednesday", "Friday"}     };     foreach (string str in args) {       int row, colm;       for (row = 0; row <= 1; ++row)         for (colm = 0; colm <= 2; ++colm)           if (str == table[row,colm])             goto done;       Console.WriteLine("{0} not found", str);       continue;     done:       Console.WriteLine("Found {0} at [{1}][{2}]", str, row, colm);     }   } } 
a goto statement is used to transfer control out of a nested scope. end note]



  

相关话题

  C# 如何在调用控件时做到 Thread-safe(线程安全)? 
  为什么 Java 只有值传递,但 C# 既有值传递,又有引用传递,这种语言设计有哪些好处? 
  在程序里如何一本正经的胡说八道? 
  如何看待即将发布的 C# 8.0? 
  用 C# 写个方法解析简单的 JSON 字符串有哪些思路? 
  大三下学期了,比较熟悉C#但哪都看到JAVA薪资和发展都比.net好,想转学JAVA,还来得及吗? 
  C# 写的程序如何测试效率, 知道哪快代码有问题? 
  如何看待ASP.NET 5 is dead? 
  Facebook 为什么不用 .NET? 
  为什么现在招聘程序员大多要求 Java / C / C++ 技能,而 C# / .NET 不受青睐? 

前一个讨论
样式(presentation)和内容(content)分别指什么?总能分离吗?
下一个讨论
为什么淘宝直通车采用 CPC,不采用 CPS?





© 2025-05-14 - tinynew.org. All Rights Reserved.
© 2025-05-14 - tinynew.org. 保留所有权利