委托与事件

 

委托是对函数的封装,可以当做给方法的特征指定一个名称。而事件则是委托的一种特殊形式,当发生有意义的事情时,事件对象处理通知过程。

委托是一种引用方法的类型。一旦为委托分配了方法,委托将与该方法具有完全相同的行为。

在发生其他类或对象关注的事情时,类或对象可通过事件通知它们。

EventArgs 是包含事件数据的类的基类。

 1     public class Cat
 2     {
 3         private string name;
 4 
 5         public Cat(string name)
 6         {
 7             this.name = name;
 8         }
 9 
10         public delegate void CatShoutEventHandler(object sender,CatShoutEventArgs args);
11 
12         public event CatShoutEventHandler CatShout;
13 
14         public void Shout()
15         {
16             Console.WriteLine("喵,我是{0}.",name);
17 
18             if (CatShout !=null)
19             {
20                 CatShoutEventArgs e=new CatShoutEventArgs();
21                 e.Name = this.name;
22                 CatShout(this,e);
23             }
24         }
25     }
 1     public class CatShoutEventArgs : EventArgs
 2     {
 3         private string name;
 4 
 5         public string Name
 6         {
 7             get { return name; }
 8             set { name = value; }
 9         }
10     }
 1     public class Mouse
 2     {
 3         private string name;
 4 
 5         public Mouse(string name)
 6         {
 7             this.name = name;
 8         }
 9 
10         public void Run(object sender,CatShoutEventArgs args)
11         {
12             Console.WriteLine("老猫{0}来了,{1} 快跑!",args.Name,name);
13         }
14     }
 1         static void Main(string[] args)
 2         {
 3             Cat cat=new Cat("Tom");
 4 
 5             Mouse mouse1=new Mouse("Jerry");
 6             Mouse mouse2=new Mouse("Jack");
 7 
 8             cat.CatShout += new Cat.CatShoutEventHandler(mouse1.Run);
 9             cat.CatShout += new Cat.CatShoutEventHandler(mouse2.Run);
10 
11             cat.Shout();
12 
13             Console.Read();
14         }

 

posted @ 2017-08-23 15:51  风中寻觅  阅读(144)  评论(0)    收藏  举报