前言
委托是对函数的封装,可以当做给方法的特征指定一个名称。而事件则是委托的一种特殊形式,当发生有意义的事的时候,事件对象 处理通知过程。[toc]
- 委托是一种引用方法的类型。一旦为委托分配了方法,委托就与该方法具有完全相同的行为。
- 事件是对委托的封装,被用于表示一个委托对象,
- 事件是在发生其它类或对象关注的事情的时候,类或对象可通过事件通知他们。
- 委托用delegate声明,事件用event声明。
- 事件只能被外部订阅,不能在外部触发,而委托没有这个限制。
初始版本
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
| using System;
internal class Program { static void Main(string[] args) { Cat cat = new Cat("Tom"); Mouse mouse1 = new Mouse("Jerry"); Mouse mouse2 = new Mouse("Jack");
cat.CatShoutEventHandler += mouse1.Run; cat.CatShoutEventHandler += mouse2.Run; cat.Shout(); } }
class Cat { private string name;
public Cat(string name) { this.name = name; }
public delegate void CatShoutDelegate(object sender, CatShoutEventArgs catShoutEventArgs);
public event CatShoutDelegate CatShoutEventHandler;
public void Shout() { Debug.Log("喵,我是" + name); if (CatShoutEventHandler != null) { CatShoutEventArgs e = new CatShoutEventArgs(); e.Name = this.name; CatShoutEventHandler(this, e); } } }
class Mouse { private string name;
public Mouse(string name) { this.name = name; }
public void Run(object sender, CatShoutEventArgs args) { Debug.Log(args.Name + "来了," + name + "快跑!"); } }
public class CatShoutEventArgs : EventArgs { public string Name { get; set; } }
public class Debug { public static void Log(string content) { Console.WriteLine(content); } }
|
简化版本
系统内置了EventHandler这个委托类,我们可以直接使用这个泛型委托类来简化我们的代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
| using System;
internal class Program { static void Main(string[] args) { Cat cat = new Cat("Tom"); Mouse mouse1 = new Mouse("Jerry"); Mouse mouse2 = new Mouse("Jack");
cat.CatShoutEventHandler += mouse1.Run; cat.CatShoutEventHandler += mouse2.Run; cat.Shout(); } }
class Cat { private string name;
public Cat(string name) { this.name = name; }
public event EventHandler<CatShoutEventArgs> CatShoutEventHandler;
public void Shout() { Debug.Log("喵,我是" + name); if (CatShoutEventHandler != null) { CatShoutEventArgs e = new CatShoutEventArgs(); e.Name = this.name; CatShoutEventHandler(this, e); } } }
class Mouse { private string name;
public Mouse(string name) { this.name = name; }
public void Run(object sender, CatShoutEventArgs args) { Debug.Log(args.Name + "来了," + name + "快跑!"); } }
public class CatShoutEventArgs : EventArgs { public string Name { get; set; } }
public class Debug { public static void Log(string content) { Console.WriteLine(content); } }
|