递归的应用
递归的定义:一个过程或函数在其定义或说明中有直接或间接调用自身的一种方法,它通常把一个大型复杂的问题层层转化为一个与原问题相似的规模较小的问题来求解,递归策略只需少量的程序就可描述出解题过程所需要的多次重复计算,大大地减少了程序的代码量。递归的能力在于用有限的语句来定义对象的无限集合。一般来说,递归需要有边界条件、递归前进段和递归返回段。当边界条件不满足时,递归前进;当边界条件满足时,递归返回
递归在实际的项目中的应用其实也有很多,比如:无限级联菜单,菜单控制管理,网站栏目设置等等,这些问题对于一个老鸟来讲是一个比较简单的问题,对于一个新手来讲可能要费点神,很容易出现死循环等异常,下面详细讲解一个在项目中经常会碰到的一种递归的方法,递归树型控件。
递归对象:
//AM_Department public class AM_Department { /// <summary> /// ID /// </summary> public virtual long ID { get; set; } /// <summary> /// 部门名称 /// </summary> public virtual string DepartmentName { get; set; } /// <summary> /// 父级部门ID /// </summary> public virtual long ParentID { get; set; } /// <summary> /// 排序级别 /// </summary> public virtual int DisplayOrder { get; set; } /// <summary> /// Dec /// </summary> public virtual string Dec { get; set; } }
递归方法
// 遍历父菜单 public static void BindTreeOfHandler(TreeView TreeList) { Organization OranObjBll = new Organization(); IList<AM_Department> deptList = OranObjBll.GetAmDepartmentInfo(); // 查询Am_Department对象 string rootstr = "菜单管理"; TreeNode rootNode = new TreeNode(rootstr); rootNode.Value = "-1"; rootNode.Target = ""; rootNode.Expanded = true; sBuffer.Clear(); sBuffer.Append("AddOrganization.aspx?organizationid="); sBuffer.Append(0); sBuffer.Append("&&organizationname="); sBuffer.Append(HttpUtility.UrlEncode(rootstr)); rootNode.NavigateUrl = sBuffer.ToString(); PopulateTreeViewOfHandler(deptList, 0, rootNode); // 遍历子项 TreeList.Nodes.Add(rootNode); }
// 遍历子菜单 private static void PopulateTreeViewOfHandler(IList<AM_Department> deptList, long parentid, TreeNode parentNode) {
// 缓存Ilist集合 IList<AM_Department> ListAmDepartObj = (from dept in deptList where dept.ParentID == parentid select dept).ToList<AM_Department>(); foreach (var listpartment in ListAmDepartObj) { TreeNode OrganizeMode = new TreeNode(listpartment.DepartmentName); OrganizeMode.Value = listpartment.ID.ToString(); OrganizeMode.Expanded = true; OrganizeMode.Target = ""; sBuffer.Clear(); sBuffer.Append("AddOrganization.aspx?organizationid="); sBuffer.Append(HttpUtility.UrlEncode(listpartment.ID.ToString())); sBuffer.Append("&&organizationparentid="); sBuffer.Append(HttpUtility.UrlEncode(parentid.ToString())); sBuffer.Append("&&organizationname="); sBuffer.Append(HttpUtility.UrlEncode(listpartment.DepartmentName)); OrganizeMode.NavigateUrl = sBuffer.ToString(); parentNode.ChildNodes.Add(OrganizeMode); // 将子树加到父菜单中 PopulateTreeViewOfHandler(deptList, listpartment.ID, OrganizeMode); // 递归 } }
调用:
BindTreeOfHandler(tree_list)
总结:
在应用中可以把递归单独封装一个操作类,把所需的操作的控件,用对象的方式传递,这样客户端的代码就会很少,也符合单一职责原则。