给组合模式中的组合对象付初始值
我学习组合模式的时候,是学习如何把数据从组合对象中读取出来的,当时觉得学有所得,现在回头想想怎么把数据装入组合对象,就有点头大,不过幸好,经过一番努力,不负所望。
在下面的代码中,实现如下功能:
本类是一个部门对象,部门下面有子部门。
1:创建了一个组合对象。
2:对象中存储着该部门的信息。
3:该对象中存储着它的子部门对象(也是组合对象)。
4:用户可以自己设置事件来完成操作该对象的任务,它的参数是对象本身。
代码如下:
using System;
using System.Data;
using System.Collections;
namespace Data
{
/// <summary>
/// 递归树组合类。
/// </summary>
/// <author>天志</author>
/// <log date="2006-06-23">创建</log>
public class DeptTreeDT
{
/// <summary>
/// 设置树节点的操作。
/// </summary>
/// <author>天志</author>
/// <log date="2006-06-23">创建</log>
public delegate void SetTreePointHandler(DeptTreeDT detail);
/// <summary>
/// 设置树节点的操作。
/// </summary>
/// <author>天志</author>
/// <log date="2006-06-23">创建</log>
public event SetTreePointHandler SetTreePoint;
/// <summary>
/// 对象。
/// </summary>
/// <author>天志</author>
/// <log date="2006-06-23">创建</log>
public DepartDT depart;
/// <summary>
/// 子。
/// </summary>
/// <author>天志</author>
/// <log date="2006-06-23">创建</log>
ArrayList arr = null;
public DeptTreeDT()
{
}
public DeptTreeDT(DataRowView dr)
{
depart = new DepartDT();
// 设置值
depart.SetData(dr);
}
/// <summary>
/// 添加节点。
/// </summary>
/// <param name="detail">节点</param>
/// <param name="dt">数据源</param>
/// <author>天志</author>
/// <log date="2006-06-23">创建</log>
public void Add(DeptTreeDT detail, DataTable dt)
{
// 如果数组为空,创建数组
if (arr == null)
{
arr = new ArrayList();
}
// 添加子
arr.Add(detail);
// 如果子有下级,递归
DataView dv = dt.DefaultView;
dv.RowFilter = "FGUID=" + detail.depart.DepGUID;
for( int i = 0; i < dv.Count; i++)
{
DeptTreeDT deptTree = new DeptTreeDT(dv[i]);
detail.Add(deptTree, dt);
dv.RowFilter = "FGUID=" + detail.depart.DepGUID;
}
}
/// <summary>
/// 移除节点。
/// </summary>
/// <param name="detail">节点</param>
/// <author>天志</author>
/// <log date="2006-06-23">创建</log>
public void Remove(DeptTreeDT detail)
{
if (arr != null)
{
arr.Remove(detail);
}
}
/// <summary>
/// 设置递归树。
/// </summary>
/// <param name="obj">未定参数</param>
/// <author>天志</author>
/// <log date="2006-06-23">创建</log>
public void Process()
{
// 设置节点
SetTreePoint(this);
if (arr != null)
{
foreach (DeptTreeDT deptTree in arr)
{
// 注册事件
deptTree.SetTreePoint += SetTreePoint;
// 递归调用
deptTree.Process();
}
}
}
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构