加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

在vb.net中打破/退出嵌套

发布时间:2020-12-17 07:32:14 所属栏目:百科 来源:网络整理
导读:我如何离开嵌套或在vb.net循环? 我尝试使用退出,但它跳或破坏只有一个for循环。 我该如何做到以下: for each item in itemList for each item1 in itemList1 if item1.text = "bla bla bla" then exit for end if end forend for 不幸的是,没有退出两个
我如何离开嵌套或在vb.net循环?

我尝试使用退出,但它跳或破坏只有一个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
不幸的是,没有退出两个级别的for语句,但有几个解决方法来做你想要的:

> Goto。一般来说,使用goto是considered to be bad practice(正确地是这样),但是使用goto仅用于结构化控制语句的正向跳转通常被认为是OK,特别是如果替代是要有更复杂的代码。

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,因为这将创建一个局部变量的闭包。
>布尔变量:这可能会使您的代码可读性略差,具体取决于您有多少层嵌套循环:

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读