在 vb.net 中中断/退出嵌套 [英] Breaking/exit nested for in vb.net

查看:28
本文介绍了在 vb.net 中中断/退出嵌套的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何摆脱 vb.net 中的嵌套 for 或循环?

How do I get out of nested for or loop in vb.net?

我尝试使用 exit for 但它只跳或中断了一个 for 循环.

I tried using exit for but it jumped or breaked only one for loop only.

我怎样才能做到以下几点:

How can I make it for the following:

for each item in itemList
     for each item1 in itemList1
          if item1.text = "bla bla bla" then
                exit for
          end if
     end for
end for

推荐答案

不幸的是,没有 exit 两级 for 语句,但有一些解决方法可以做你想做的事:

Unfortunately, there's no exit two levels of for statement, but there are a few workarounds to do what you want:

  • 转到.一般来说,使用 goto认为是不好的做法(并且理所当然地所以),但仅将 goto 用于结构化控制语句的向前跳转通常被认为是可以的,特别是如果替代方案是具有更复杂的代码.

  • Goto. In general, using goto is considered to be bad practice (and rightfully so), but using goto solely for a forward jump out of structured control statements is usually considered to be OK, especially if the alternative is to have more complicated code.

For Each item In itemList
    For Each item1 In itemList1
        If item1.Text = "bla bla bla" Then
            Goto end_of_for
        End If
    Next
Next

end_of_for:

  • 虚拟外层块

    Do
        For Each item In itemList
            For Each item1 In itemList1
                If item1.Text = "bla bla bla" Then
                    Exit Do
                End If
            Next
        Next
    Loop While False
    

    Try
        For Each item In itemlist
            For Each item1 In itemlist1
                If item1 = "bla bla bla" Then
                    Exit Try
                End If
            Next
        Next
    Finally
    End Try
    

  • 单独的函数:将循环放在一个单独的函数中,可以用return退出.不过,这可能需要您传递大量参数,具体取决于您在循环内使用的局部变量的数量.另一种方法是将块放入多行 lambda 中,因为这将在局部变量上创建一个闭包.

  • Separate function: Put the loops inside a separate function, which can be exited with return. This might require you to pass a lot of parameters, though, depending on how many local variables you use inside the loop. An alternative would be to put the block into a multi-line lambda, since this will create a closure over the local variables.

    布尔变量:这可能会使您的代码可读性稍差,具体取决于您有多少层嵌套循环:

    Boolean variable: This might make your code a bit less readable, depending on how many layers of nested loops you have:

    Dim done = False
    
    For Each item In itemList
        For Each item1 In itemList1
            If item1.Text = "bla bla bla" Then
                done = True
                Exit For
            End If
        Next
        If done Then Exit For
    Next
    

  • 这篇关于在 vb.net 中中断/退出嵌套的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆