懂得放弃,才会有新的收获!

简单易懂的C#委托与事件

By weisnet On 2010-04-21 At 21:23 View:198

委托与事件就好比食堂有个厨师,做了很多道的菜,但是他不知道每个顾客要点什么菜。

顾客是来吃厨师做的菜的,但每个的喜好不一样,有的要点A菜,有的要点B菜。

厨师做的这些菜都放在一个菜架窗口里,顾客都可以看得见,当看到自己喜欢的菜时,就手指一下,或叫出菜的名子,让打菜员给你夹到盘子上。 

菜架窗口:Class Life

A菜,B菜,C菜:Method (EatA(),EatB(), .......)
代码:


C#
  1. public class Life
  2.     {
  3.         public delegate void LifeGate();
  4.         public event LifeGate lifeEvent;
  5.         public event LifeGate event2;
  6.         public void LifeAll(string lifeType)
  7.         {
  8.             if (lifeType ="=" "GoBed")
  9.             {
  10.                 if (event2 != null)
  11.                 {
  12.                     event2();
  13.                 }
  14.             }
  15.             else if (lifeType ="=" "Eat")
  16.             {
  17.                 if (lifeEvent != null)
  18.                 {
  19.                     lifeEvent();
  20.                 }
  21.             }
  22.             else
  23.             {
  24.             }
  25.         }
  26.         //eat
  27.         public void EatA()
  28.         {
  29.             Console.WriteLine("我要吃A的东西!");
  30.         }
  31.         public void EatB()
  32.         {
  33.             Console.WriteLine("我要吃B的东西!");
  34.         }
  35.         public void EatC()
  36.         {
  37.             Console.WriteLine("我要吃C的东西!");
  38.         }
  39.         //gobed
  40.         public void GoBedA()
  41.         {
  42.             Console.WriteLine("我要睡A的床");
  43.         }
  44.         public void GoBedB()
  45.         {
  46.             Console.WriteLine("我要睡B的床");
  47.         }
  48.         public void GoBedC()
  49.         {
  50.             Console.WriteLine("我要睡C的床");
  51.         }
  52.     }

  
C#
  1. class Program
  2.     {
  3.         static void Main(string[] args)
  4.         {
  5.             Life f = new Life();
  6.             f.lifeEvent += f.EatA;
  7.             f.lifeEvent += f.EatC;
  8.             f.lifeEvent -= f.EatA;
  9.             f.lifeEvent += f.EatB;
  10.             f.LifeAll("Eat");
  11.             Console.WriteLine("finished Eat");
  12.             f.event2 += f.GoBedB;
  13.             f.LifeAll("GoBed");
  14.             Console.WriteLine("finished GoBed");
  15.             ConsoleKeyInfo cki;
  16.             while (true) { cki = Console.ReadKey(true); if (cki.Key ="=" ConsoleKey.Enter) break; }
  17.         }
  18.     }

 
Life是菜窗口...里面有厨师做的所有菜...
Program 是顾客:从中可以看出顾客选出B,C两道菜!

·上一篇:Sql Server 2005 数据表分区优化数据库
·下一篇:Javascript摸拟自由落体与上抛运动

for this post

 
 

Leave a Reply

赶快抢个沙发坐坐!
请先 登陆  还没帐号

Hot Posts Powered by weiseditor

  • Add to Google

Friend links