class PubEventArgs : EventArgs { private readonly string _magname; public string Magname { get { return _magname; } } public PubEventArgs(string magname) { _magname = magname; } } class Event//創建事件類 { public delegate void PubComputerEventHandle(object sender,PubEventArgs e);//聲明委托 public event PubComputerEventHandle PubComputer;//創建委托鏈,即事件 public delegate void PubLifeEventHandle(object sender, PubEventArgs e); public event PubLifeEventHandle PubLife; public virtual void OnComputer(PubEventArgs e) { PubComputerEventHandle handle = PubComputer; if (handle != null) { handle(this,e); } } public virtual void OnLife(PubEventArgs e) { PubLifeEventHandle handle = PubLife; if (handle != null) { handle(this, e); } } public void IsComputer(string magname)//創建觸發事件過程 { Console.WriteLine("發行"+magname+"雜志"); OnComputer(new PubEventArgs(magname)); } public void IsLife(string magname) { Console.WriteLine("發行" + magname + "雜志"); OnComputer(new PubEventArgs(magname)); } } class Man//創建操作主體 { public string name; public Man(string name) { this.name = name; } public void Order(object sender, PubEventArgs e)//在主體中創建被委托的函數 { Console.WriteLine(name + "訂閱" + e.Magname + "刊物"); } } class Program { static void Main(string[] args) { Event e = new Event();//事件建好 Man zs = new Man("張三");//主體建好 e.PubComputer += new Event.PubComputerEventHandle(zs.Order);//調用主體的被委托函數 Man ls = new Man("李四"); e.PubComputer += new Event.PubComputerEventHandle(ls.Order); e.PubLife += new Event.PubLifeEventHandle(ls.Order); e.IsComputer("電腦");//觸發事件 e.IsLife("生活"); Console.Read(); } }