简体   繁体   English

继续<label>在C#中像java一样</label>

[英]continue to <label> in C# like in java

I need C# equivalent to Java's continue ? 我需要C#相当于Java的继续吗?

i have 我有

for (String b : bar) {
    <label>
    try {
    }
    catch (EndpointNotFoundException ex) {
    continue <label>
    }
  }

how can i simulate this in C#. 我怎样才能在C#中模拟这个。 i need that when i get exception that i repeat code not go on. 我需要的是,当我得到异常,我重复代码不继续。

If you only need to continue to the next loop iteration, use continue . 如果您只需要继续下一个循环迭代,请使用continue

c# also has labels (which you can jump to with goto ), but please don't use them. c#也有标签(你可以跳转到goto ),但请不要使用它们。

使用goto <label>;

Why not simply add a control variable? 为什么不简单地添加一个控制变量?

foreach (String b in bar) {
  bool retry;
  do {
    retry = false;
    try {
      // ...
    }
    catch (EndpointNotFoundException ex) {
      retry = true;
    }
  } while (retry);
}

or 要么

var strings = bar.GetEnumerator<string>();
var retry = false;
while (retry || strings.Next()) {
  var b = strings.Current;
  retry = false;
  try {
    // ...
  }
  catch (EndpointNotFoundException ex) {
    retry = true;
  }
}

I don't think what you're trying to do is wise at all - do you have any reason to expect that you won't hit a scenario where you always get an exception on a particular iteration? 我不认为你想要做的事情是明智的 - 你有没有理由期望你不会遇到一个你在特定迭代中总是得到异常的情况?

Anyhow, to do what you want to do without goto , look at this: 无论如何,要在没有goto情况下做你想做的事,看看这个:

foreach (String b in bar) { 
    while(!DidSomethingWithThisString(b))
        ;
  } 

bool DidSomethingWithThisString(string b)
{
    try { 
    } 
    catch (EndpointNotFoundException ex) { 
        return false;
    } 
    return true;
}

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

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