NET-如何移动到下一个项目为每个循环?

是否有类似于 Exit For的语句,除非它没有退出循环,而是移动到下一个项目。

例如:

For Each I As Item In Items


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


' Do something


Next

我知道可以简单地在 If 语句中添加一个 Else,使其内容如下:

For Each I As Item In Items


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


Next

只是想知道是否有一种方法可以跳到 Items列表中的下一个项目。我确信大多数人会问为什么不仅仅使用 Else语句,而且对我来说包装“ Do Something”代码似乎不太可读。特别是当有很多代码的时候。

160907 次浏览
For Each I As Item In Items
If I = x Then Continue For


' Do something
Next

I'd use the Continue statement instead:

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 If will be executed again. Usually this is what you want, but if not you'll have to use GetEnumerator() and then MoveNext()/Current explicitly rather than using a For Each loop.

What about:

If Not I = x Then


' Do something '


End If


' Move to next item '

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

For Each I As Item In Items


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


' Do something
Label1:
Next

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

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.

Only the "Continue For" is an acceptable standard (the rest leads to "spaghetti code").

At least with "continue for" the programmer knows the code goes directly to the top of the loop.

For purists though, something like this is best since it is pure "non-spaghetti" code.

Dim bKeepGoing as Boolean
For Each I As Item In Items
bKeepGoing = True
If I = x Then
bKeepGoing = False
End If
if bKeepGoing then
' Do something
endif
Next

For ease of coding though, "Continue For" is OK. (Good idea to comment it though).

Using "Continue For"

For Each I As Item In Items
If I = x Then
Continue For   'skip back directly to top of loop
End If
' Do something
Next