program.cs
来自「这是asp.net^和Visual C++Sharp编写的串并口通讯的书籍 源代」· CS 代码 · 共 68 行
CS
68 行
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
namespace _2
{
abstract class AComponent
{
protected string name;
public AComponent(string name)
{
this.name = name;
}
public abstract void Display(int deep);
}
// 合成
class Composite : AComponent
{
private ArrayList children = new ArrayList();
public Composite(string name) : base(name) { }
public void Add(AComponent c)
{
children.Add(c);
}
public void Remove(AComponent c)
{
children.Remove(c);
}
public override void Display(int deep)
{
Console.WriteLine(new String('*', deep) + name);
// 输出每一个子节点。
foreach (AComponent c in children)
c.Display(deep + 2);
}
}
// 子项
class Leaf : AComponent
{
public Leaf(string name) : base(name) { }
public override void Display(int deep)
{
Console.WriteLine(new String('-', deep) + name);
}
}
public class Client
{
public static void Main(string[] args)
{
// Create a tree structure
Composite root = new Composite("根目录");
root.Add(new Leaf("子项 A"));
root.Add(new Leaf("子项 B"));
Composite comp = new Composite("合成 X");
comp.Add(new Leaf("子项 XA"));
comp.Add(new Leaf("子项 XB"));
root.Add(comp);
root.Add(new Leaf("子项 C"));
//添加和移除子项
Leaf l = new Leaf("子项 D");
root.Add(l);
root.Remove(l);
root.Display(1);
}
}
}
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?