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

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