1.委托的含义:
(MSDN)A delegate declaration defines a reference type that can be used to encapsulate a method with a specific signature.A delegate instance encapsulates a static or an instance method.Delegates are roughly similar to function pointers in C++;however,delegates are type-safe and secure.
委托是一种引用方法的类型。一旦为委托分配了方法,委托将与该方法具有完全相同的行为。委托方法的使用可以像其他任何方法一样,具有参数和返回值。
猫和老鼠的例子(1) //定义一个委托,用来关联的Cry事件处理方法 publicdelegatevoid CryEventHandler(); //Cat类是事件的生成者,通过OnCry()方法引发Cry事件 //但Cat类并不知道谁会监听Cry事件,以及如何理Cry事件,它只是告诉环境Cry事件发生了 //通俗的解释是:猫叫了,但猫并不知道它的叫声对环境有什么影响 publicclass Cat { //定义事件,表示猫叫 publicstaticevent CryEventHandler Cry; public Cat() { Console.WriteLine("Cat:I'm coming."); } publicvirtualvoid OnCry() { Console.WriteLine("Cat:MiaoMiao"); if (Cry !=null) { Cry(); } } } //Mouse类是事件的订阅者,定义了Cry事件发生时的处理方法Run() //通俗的解释是:老鼠在夜间行动时,时刻都在堤防着猫,如果听到猫叫声马上离开 publicclass Mouse { public Mouse() { Cat.Cry +=new CryEventHandler(Run); Console.WriteLine("Mouse:I go to find something,and I must always listen cat's crying."); } publicvoid Run() { Console.WriteLine("Mouse:A cat is coming,I must go back!"); } } publicclass Demo1 { publicstaticvoid Main(string[] args) { Mouse mouse =new Mouse(); Cat cat =new Cat(); cat.OnCry(); Console.ReadLine(); } }
运行后控制台输出为:
Cat:Mouse:I go to find something,and I must always listen cat's crying. I'm coming. Cat:MiaoMiao... Mouse:A cat is coming,I must go back!
运行后控制台输出为: Mouse:I go to find something,and I must always listen cat's crying. Cat:aBenCat coming. Cat:MiaoMiao... Mouse:aBenCat,I am not afraid! Cat:smartCat coming. Cat:MiaoMiao... Mouse:smartCat,I must run!
1.委托的含义: (MSDN)A delegate declaration defines a reference type that can be used to encapsulate a method with a specific signature.A delegate instance encapsulates a static or an instance metho