中断/退出嵌套在vb.net [英] Breaking/exit nested for in vb.net
问题描述
我试过使用exit,但是它跳过或者只打开一个for循环。 / p>
我怎样才能做到这一点:
in itemList
for itemList1中的每个item1
if item1.text =bla bla blathen
exit for
end if
end for
end for
不幸的是,没有 的转到即可。一般来说,使用 虚拟外部区块 或 单独的函数:将循环放在一个单独的函数中,可以用 exit两个级别的
语句,但有几个解决方法可以做你想做的:
goto
是被认为是不好的做法(而且也是这样),但是仅仅为了跳出结构化控制语句而使用 goto
通常被认为是可以的,特别是如果替代方案是有更多复杂的代码。
对于每个项目在itemList
对于每个item1在itemList1
如果item1.Text = bla bla blaThen
Goto end_of_for
End If
Next
Next
end_of_for:
do
对于每个item在itemList中
对于每个item1在itemList1中
如果item1.Text =bla bla blaThen
Exit Do
End If
下一个
下一个
Loop While False
尝试
对于每个项目在项目列表
对于每个item1在itemlist1
如果item1 =bla bla bla则
退出Try
结束如果
下一个
下一个
最后
结束尝试
return
来退出。这可能需要您传递很多参数,具体取决于您在循环中使用了多少个局部变量。另一种方法是把块放到一个多行的lambda中,因为这会在局部变量上创建一个闭包。
Dim done = False
对于每个item在itemList
对于每个item1在itemList1
如果item1.Text =bla bla bla那么
完成= True
退出对于
结束如果
下一个
如果完成然后退出
下一个
How do I get out of nested for or loop in vb.net?
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
Unfortunately, there's no exit two levels of for
statement, but there are a few workarounds to do what you want:
Goto. In general, using
goto
is considered to be bad practice (and rightfully so), but usinggoto
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:
Dummy outer 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
or
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
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屋!