微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

vb.net 如何退出递归循环

如何解决vb.net 如何退出递归循环

我正在为 3D 程序 CATIA 编写代码,该代码通过递归循环遍历所有树。在找到特定产品后,我想退出递归循环。但是我的代码一直在运行,即使他找到了。我写的大致意思。我在那里做错了什么?

Private Sub TestMain
   .....
   call TestMainChildren
   .....
End Sub

Private Sub TestMainChildren
  For Each item In product
      .....
      If itemName = "SearchName" then
         MsgBox("Found!")
         Exit Sub
      End if
      ......
      Call TestMainChildren
   Next
End Sub

enter image description here

解决方法

地点

exit for

在循环内满足条件后

已编辑//

Private Sub TestMain
 .....
 call TestMainChildren
 .....
End Sub

Private Sub TestMainChildren
   For Each item In product
    .....
     If itemName = "SearchName" then
      MsgBox("Found!")
      Exit for
  End if
  ......
  'Call TestMainChildren - delete this
   Next
End Sub
,

为了使这个递归,您需要将一个起始对象传递给函数,在本例中为 products。然后,当您查看子对象时,仅递归传递产品集合。

Private Sub TestMain    
    Dim searchName As String
    searchName = "SearchName"

    ' Start with the selected object
    Dim doc As Document
    Set doc = CATIA.ActiveDocument
    Dim prod As Product
    Set prod = doc.Product

    Dim foundItem As Object
    foundItem = TestMainChildren(doc.Selection.Item(1).Value,searchName)

    MsgBox "Found: " & foundItem.Name
End Sub

Private Function TestMainChildren(ByRef catiaObject As Object,ByVal searchName As String) As Object
    Dim item As Object
    For Each item In catiaObject.Items
        If item.Name = "SearchName" then
            Set TestMainChildren = item
            Exit For
        End if

        Dim catiaType As String
        catiaType = TypeName(item)
        If catiaType = "Product" Then
            TestMainChildren item,searchName
        End If
    Next
End Sub

警告:这是完全未经测试的蒸气器。您必须对其进行修改以适应您的环境和要求。然后进行适当的测试和调试。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。