码迷,mamicode.com
首页 > 其他好文 > 详细

循环递归+返回值(TreeView示例)

时间:2014-12-13 23:15:45      阅读:311      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   io   ar   color   使用   sp   for   

示例:获取TreeView的所有Node,保存到List<TreeNode>,封装到通用工具类:

方法一:使用static方法、属性---调用前清空static类型的List

 1         public static List<TreeNode> allNodes = null;
 2         public static void GetTreeViewAllNodes(TreeNodeCollection Nodes)
 3         {
 4             foreach (TreeNode node in Nodes)
 5             {
 6                 allNodes.Add(node);
 7                 if (node.ChildNodes.Count > 0)
 8                 {
 9                     GetTreeViewAllNodes(node.ChildNodes);
10                 }
11             }
12         }
13         public static List<TreeNode> GetNodes(TreeView tv)
14         {
15             GetTreeViewAllNodes(tv.Nodes);
16             return allNodes;
17         } 
注意:如果使用static类型的List,每次调用该通用工具类之前需要清空List<TreeNode>,否则会出现叠加。在构造函数中清空:
public Tools()
{
      allNodes.Clear();   
}

方法二、使用内部方法、属性---直接调用

 1         public List<TreeNode> allNodes = new List<TreeNode>();
 2         public void GetTreeViewAllNodes(TreeNodeCollection Nodes)
 3         {
 4             foreach (TreeNode node in Nodes)
 5             {
 6                 allNodes.Add(node);
 7                 if (node.ChildNodes.Count > 0)
 8                 {
 9                     GetTreeViewAllNodes(node.ChildNodes);
10                 }
11             }
12         }
13         public List<TreeNode> GetNodes(TreeView tv)
14         {
15             GetTreeViewAllNodes(tv.Nodes);
16             return allNodes;
17         }

疑问:能不能使用一个方法既可以实现循环遍历,又可以获得返回值???

循环递归+返回值(TreeView示例)

标签:des   style   blog   io   ar   color   使用   sp   for   

原文地址:http://www.cnblogs.com/wanshi1989/p/4161958.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!