VB.NET - 如何移动到 For Each 循环的下一项?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/829689/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 14:12:49  来源:igfitidea点击:

VB.NET - How to move to next item a For Each Loop?

vb.netloops

提问by Sean Taylor

Is there a statment like Exit For, except instead of exiting the loop it just moves to the next item.

是否有类似 的语句Exit For,除了不是退出循环,它只是移动到下一项。

For example:

例如:

For Each I As Item In Items

    If I = x Then 
        ' Move to next item
    End If

    ' Do something

Next

I know could simply add an Elseto the If statement so it would read as follows:

我知道可以简单Else地在 If 语句中添加一个,这样它就会如下所示:

For Each I As Item In Items

    If I = x Then 
        ' Move to next item
    Else
        ' Do something
    End If

Next

Just wondering if there is a way to jump to the next item in the Itemslist. I'm sure most will properly be asking why not just use the Elsestatement, but to me wrapping the "Do Something" code seems to be less readable. Especially when there is a lot more code.

只是想知道是否有办法跳转到Items列表中的下一项。我相信大多数人会正确地问为什么不直接使用该Else语句,但对我来说,包装“做某事”代码似乎不太可读。特别是当有更多的代码时。

回答by Adam Robinson

For Each I As Item In Items
    If I = x Then Continue For

    ' Do something
Next

回答by Jon Skeet

I'd use the Continuestatement instead:

我会改用以下Continue语句:

For Each I As Item In Items

    If I = x Then
        Continue For
    End If

    ' Do something

Next

Note that this is slightly different to moving the iterator itself on - anything before the Ifwill be executed again. Usually this is what you want, but if not you'll have to use GetEnumerator()and then MoveNext()/Currentexplicitly rather than using a For Eachloop.

请注意,这与移动迭代器本身略有不同 -If将再次执行之前的任何内容。通常这就是您想要的,但如果不是,您将不得不使用GetEnumerator()and then MoveNext()/Current显式而不是使用For Each循环。

回答by timo2oo8

What about:

关于什么:

If Not I = x Then

  ' Do something '

End If

' Move to next item '

回答by Syed Tayyab Ali

I want to be clear that the following code is not good practice.You can use GOTO Label:

我想清楚以下代码不是好的做法。您可以使用 GOTO 标签:

For Each I As Item In Items

    If I = x Then
       'Move to next item
        GOTO Label1
    End If

    ' Do something
    Label1:
Next

回答by Karmendra

When I tried Continue Forit Failed, I got a compiler error. While doing this, I discovered 'Resume':

当我尝试Continue For失败时,出现编译器错误。这样做时,我发现了“简历”:

For Each I As Item In Items

    If I = x Then
       'Move to next item
       Resume Next
    End If

    'Do something

Next

Note: I am using VBA here.

注意:我在这里使用 VBA。