控制迭代循环内部的递归

时间:2016-02-22 06:47:38

标签: .net vb.net algorithm recursion iteration

我正在尝试构建一个属性检查器方法,该方法迭代地检查所有对象属性,并递归检查这些属性的所有子属性,直到它用完属性或达到最大递归级别/深度。

然而,由于递归发生在迭代循环内部,因此我在跟踪递归深度时遇到了问题,因此对象的每个属性都会递增递归深度,而不应该递增递归深度。水平下降应该。

这是我的示例代码:

Dim MaxRecursionLevel As Integer = 10
Dim CurrentRecursionLevel As Integer = 1

Function GetPropertiesWithName(objToSearch as Object, optional nameFilters as String()

dim result as new List(of Object)
If CurrentRecursionLevel > MaxRecursionLevel Then Exit Function
CurrentRecursionLevel = CurrentRecursionLevel + 1

'Iteration of properties
For Each item As PropertyInfo In objToSearch.GetType.GetProperties() 
    if PropertyHasName(nameFilters) Then
        result.Add(item)
        dim subItem as Object = item.GetValue(objToSearch, Nothing)

        'Recursion of Subproperties
        dim subResult as List(of Object) = GetPropertiesWithName(subItem, nameFilters)
        if not subResult is Nothing then result.Addrange(subResult)
    End If
Next
Return result
End Function

如何准确跟踪递归深度,还是有更好的方法来解决这个问题?

2 个答案:

答案 0 :(得分:3)

不是使用全局变量来跟踪递归,而是将当前递归级别作为参数传递给函数。在函数的顶部,检查传入的值是否超过最大值,如果是,则立即返回。

答案 1 :(得分:3)

对尼克斯的回答:

Function GetPropertiesWithName(objToSearch as Object, currentRecusrionLevel as Integer, optional nameFilters as String())
  If currentRecusrionLevel > MaxRecursionLevel Then Return new List(Of Object)
  '...
  For Each item As PropertyInfo In objToSearch.GetType.GetProperties() 
    '...
    Dim subResult as List(of Object) = 
         GetPropertiesWithName(subItem,currentRecusrionLevel + 1, nameFilters)
  '...