在vb.net中嵌套/退出

Koo*_*bin 118 vb.net for-loop nested-loops

如何退出vb.net中的嵌套for或循环?

我尝试使用exit,但它只跳转或断开一个for循环.

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

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
Run Code Online (Sandbox Code Playgroud)

Hei*_*nzi 194

不幸的是,没有exit two levels of for声明,但有一些解决方法可以做你想要的:

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

    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:
    
    Run Code Online (Sandbox Code Playgroud)
  • 假外块

    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
    
    Run Code Online (Sandbox Code Playgroud)

    要么

    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
    
    Run Code Online (Sandbox Code Playgroud)
  • 单独的功能:将循环放在一个单独的功能中,可以退出return.但是,这可能需要您传递大量参数,具体取决于您在循环中使用的局部变量数量.另一种方法是将块放入多行lambda中,因为这会在局部变量上创建一个闭包.

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

    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
    
    Run Code Online (Sandbox Code Playgroud)

  • 不能说除了函数之外的任何一个都比`goto`更好,如果它真的有意义的话. (3认同)
  • 我将在一个大项目中使用那个'goto`来记住我在qbasic的编程日,啊这样无辜的时候.否则我会去做假的. (2认同)

Tob*_*ski 16

将循环放在子程序中并调用 return

  • @AltianoGerung 如果有什么经验教会了我,那就是规模足够大,即使是最小的问题也会变得足够重要。与往常一样,在做出任何假设之前先进行分析。:) (2认同)

小智 5

For i As Integer = 0 To 100
    bool = False
    For j As Integer = 0 To 100
        If check condition Then
            'if condition match
            bool = True
            Exit For 'Continue For
        End If
    Next
    If bool = True Then Continue For
Next
Run Code Online (Sandbox Code Playgroud)