使用函数传递对象的ByRef成子,而不是 - 这是不好的编程习惯......为什么呢?这是、什么呢、函数、而不是

2023-09-06 16:29:48 作者:╭⌒微凉的心,碎

我创建了下面的递归程序来得到一个TreeView所有选中的节点:

I created the following recursive routine to get all the checked nodes in a treeview:

    Sub GetAllCheckedNodes(ByVal tn As TreeNode, ByRef NodesList As List(Of TreeNode))
        If tn.Checked Then NodesList.Add(tn)

        For Each nd As TreeNode In tn.Nodes
            GetAllCheckedNodes(nd, NodesList)
        Next
    End Sub

基本上,我用这将是方法来声明一个空的列表(中树节点),然后将它传递到该程序的第二个参数。 我的问题是,我已经被告知这是不伟大的编程习惯 - 为什么,什么可能出错

Basically, the way I use it would be to declare an empty List(Of Treenode) and then pass it into this routine as the second argument. My question is that I've been told this is "not great" programming practice - Why and what could go wrong?

这似乎是最优雅的解决方案,我可以拿出来得到这个工作。

It seems to be the most elegant solution I could come up with to get this to work.

推荐答案

没有必要通过列表的ByRef - 这已经是一个引用类型。只是通过它按价值计算,你仍然可以检查的项目添加到它。

There is no need to pass the list ByRef -- it's already a reference type. Just pass it by value and you'll still be able to add checked items to it.