如何退出递归循环退出

时间:2010-06-17 14:19:51

标签: vb.net recursion

如何从下面的代码中退出递归循环。我想在退出循环之前通知最终用户在msgBox中选中一个复选框。感谢。

Private Sub PrintRecursive(ByVal n As TreeNode)
    System.Diagnostics.Debug.WriteLine(n.Text)

    If (n.Checked = True) Then
        MessageBox.Show(n.Checked)
    Else
        If (n.Checked = False) Then
            MessageBox.Show("Check a bex")
        End If
        End If


        ' MessageBox.Show(n.Checked)
        Dim aNode As TreeNode
        For Each aNode In n.Nodes
            PrintRecursive(aNode)
        Next
End Sub

' Call the procedure using the top nodes of the treeview.
Private Sub CallRecursive(ByVal aTreeView As TreeView)
    Dim n As TreeNode
    For Each n In aTreeView.Nodes
        PrintRecursive(n)
    Next
End Sub

1 个答案:

答案 0 :(得分:1)

一种方法是将PrintRecursive更改为返回布尔值的函数,其中true表示“停止”

然后更改递归调用以检查返回值。

For Each aNode In n.Nodes
    if not PrintRecursive(aNode) then 
        msgbox("Notify User")
        return false
    end if
Next

尽管如此,在退出递归时,消息框将显示在每个嵌套级别。为了避免这种情况,您可以将嵌套级别的参数添加到PrintRecursive,这样您就可以知道自己何时处于最高级别。

Private Function PrintRecursive(ByVal n As TreeNode, optional byval NestLevel as Integer=0) as Boolean
...
    For Each aNode In n.Nodes
        if not PrintRecursive(aNode,NestLevel+1) then 
            if (NestLevel=0) then msgbox("Notify User")
            return false
        end if
    Next
....