Stackoverflow异常 - 递归Treeview ASP.Net

时间:2015-11-18 16:44:10

标签: asp.net vb.net recursion treeview

我正在尝试使用VB.Net递归地构建一个树视图,这是我到目前为止的代码

.... Code to get the data table 

For Each row As DataRow In dt.Rows

        Dim oName As String = Nothing
        Dim pId As String = Nothing
        Dim cId As String = Nothing
        Dim cmts As String = Nothing
        Dim lvl As String = Nothing
        oName = row(0)
        pId = row(4)
        cId = row(5)
        If Not String.IsNullOrEmpty(row(3).ToString()) Then
            cmts = row(3)
        End If
        lvl = row(2)

        list.Add(New MyObject() With { _
                                    .ObjectName = oName,
                                    .ParentId = pId,
                                    .ChildId = cId,
                                    .Comments = cmts,
                                    .level = lvl
                                })

    Next

BindTree(list, Nothing)

End Sub



Private Sub BindTree(list As IEnumerable(Of MyObject), parentNode As TreeNode)
    Dim nodes = list.Where(Function(x) If(parentNode Is Nothing, x.ParentId = "[Transform].[(Root)]", x.ParentId = parentNode.Value))
    For Each node As MyObject In nodes
        Dim newNode As New TreeNode(node.ObjectName, node.ParentId.ToString())
        If parentNode Is Nothing Then
            TreeView1.Nodes.Add(newNode)
        Else
            parentNode.ChildNodes.Add(newNode)
        End If
        BindTree(list, newNode)
    Next
End Sub

也是新班级

Public Class MyObject
Public ObjectName As String
Public ParentId As String
Public ChildId As String
Public Comments As String
Public level As Integer
End Class

我遇到的问题是,当通过递归到目前为止,我得到一个System.StackOverFlowException。在查看异常快照时,每个东西都说“无法评估表达式”错误来自此行

Dim nodes = list.Where(Function(x) If(parentNode Is Nothing, x.ParentId = "[Transform].[(Root)]", x.ParentId = parentNode.Value))但我不知道为什么或如何解决它。

非常感谢任何帮助。

由于

西蒙

1 个答案:

答案 0 :(得分:2)

特定的代码行不会引发StackOverflowException,这只是被调用的方法中第一行代码溢出堆栈。并且没有更多的信息可以真正给出,因为不能执行更多的代码。 (因为堆栈已满。)

您的方法是递归的:

Private Sub BindTree(list As IEnumerable(Of MyObject), parentNode As TreeNode)
    ' ...
    BindTree(list, newNode)
End Sub

没关系,除了你没有在任何地方修改list变量。因此,每次调用该方法时,都会使用相同的list调用它。因此,它将继续无限期地递归地执行相同的逻辑,没有终止条件。

通常,您应该考虑使用以下结构的递归方法(在VB-ish伪代码中):

Method(ByVal something As SomeType)
    ' Check if the recursion should end
    If SomeTerminatingCondition Then
        Return
    End If

    ' Perform the logic for this step of the recursion
    DoSomething()

    ' Recurse again
    Method(somethingModified)
End Method

从代码中我可以完全完全清楚list应该如何修改。但是,当您在此时调用BindTree(list, newNode) list时,应该是原始list的某些子集