标签:
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(); } }
标签:
原文地址:http://www.cnblogs.com/liujianshe1990-/p/5361881.html