委托与事件就好比食堂有个厨师,做了很多道的菜,但是他不知道每个顾客要点什么菜。
顾客是来吃厨师做的菜的,但每个的喜好不一样,有的要点A菜,有的要点B菜。
厨师做的这些菜都放在一个菜架窗口里,顾客都可以看得见,当看到自己喜欢的菜时,就手指一下,或叫出菜的名子,让打菜员给你夹到盘子上。
菜架窗口:Class Life
A菜,B菜,C菜:Method (EatA(),EatB(), .......)
代码:
|
C# |
- public class Life
- {
- public delegate void LifeGate();
- public event LifeGate lifeEvent;
- public event LifeGate event2;
- public void LifeAll(string lifeType)
- {
- if (lifeType ="=" "GoBed")
- {
- if (event2 != null)
- {
- event2();
- }
- }
- else if (lifeType ="=" "Eat")
- {
- if (lifeEvent != null)
- {
- lifeEvent();
- }
- }
- else
- {
- }
- }
- //eat
- public void EatA()
- {
- Console.WriteLine("我要吃A的东西!");
- }
- public void EatB()
- {
- Console.WriteLine("我要吃B的东西!");
- }
- public void EatC()
- {
- Console.WriteLine("我要吃C的东西!");
- }
- //gobed
- public void GoBedA()
- {
- Console.WriteLine("我要睡A的床");
- }
- public void GoBedB()
- {
- Console.WriteLine("我要睡B的床");
- }
- public void GoBedC()
- {
- Console.WriteLine("我要睡C的床");
- }
- }
|
|
C# |
- class Program
- {
- static void Main(string[] args)
- {
- Life f = new Life();
- f.lifeEvent += f.EatA;
- f.lifeEvent += f.EatC;
- f.lifeEvent -= f.EatA;
- f.lifeEvent += f.EatB;
- f.LifeAll("Eat");
- Console.WriteLine("finished Eat");
- f.event2 += f.GoBedB;
- f.LifeAll("GoBed");
- Console.WriteLine("finished GoBed");
- ConsoleKeyInfo cki;
- while (true) { cki = Console.ReadKey(true); if (cki.Key ="=" ConsoleKey.Enter) break; }
- }
- }
|
Life是菜窗口...里面有厨师做的所有菜...
Program 是顾客:从中可以看出顾客选出B,C两道菜!