【问题标题】:how do I exit from Recursive Loop Exit如何退出递归循环退出
【发布时间】:2012-05-04 00:25:40
【问题描述】:

如何从下面的代码中退出递归循环。我想在退出循环之前通知最终用户在 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

【问题讨论】:

  • 顺便说一句:只是一个温和的提醒,这是对那些花时间尝试并帮助您接受问题答案的人的预期礼貌。
  • 谢谢约翰,我对这个网站还很陌生。感谢您花时间帮助我编写代码。

标签: vb.net recursion


【解决方案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
....

【讨论】:

  • 嗨 John,我多次尝试了这段代码,但我的编译器在 部分告诉我表达式不返回价值。还有什么我应该研究的吗?另外,您认为使用这种方法是否最好循环遍历树节点中选择的所有节点?谢谢。
  • 这只是一种方法的示例,但无论如何我对代码进行了一些调整。另外,你把方法改成函数了吗?
  • 嗨,John,再次感谢您提供的编码支持以及有关成为本网站更好用户的提示。实际上,我将子过程切换到了一个函数,仍然遇到了一些问题,但似乎我并没有陷入递归循环。这个周末我的工作很忙。再次感谢。
  • 顺便说一句。我看了你的网站。您在那里发布了一些非常好的东西。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-09-15
  • 1970-01-01
  • 1970-01-01
  • 2012-11-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多