如何退出 vb.net 中的嵌套 for 或循环?
我尝试使用 exit for 但它只跳转或中断了一个 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
最佳答案
不幸的是,没有 exit 两级 for
语句,但是有一些解决方法可以完成您想要的操作:
转到。一般来说,使用
goto
是considered to be bad practice (这是正确的),但是仅使用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:
虚拟外部 block
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
退出。不过,这可能需要您传递大量参数,具体取决于您在循环内使用的局部变量数量。另一种方法是将 block 放入多行 lambda 中,因为这将在局部变量上创建一个闭包。bool 变量:这可能会降低您的代码的可读性,具体取决于您有多少层嵌套循环:
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 - 中断/退出嵌套在 vb.net 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5312291/