一直不甚至理解C#中委托和事件的概念和用法,在网上参看数篇文字之后略有所得,好记性不如烂键盘,故以文字记下。
首先,设想一个简单场景(或许不太贴切)来说明,夜深人静,屋里有老鼠蹑手蹑脚的行动,且随时提防着猫,如果听到猫叫,老鼠闻声立即逃回洞里。
这个场景可以抽象为委托和事件的几个要素:
猫和老鼠分别是两个对象,猫是激发事件的对象,猫叫是一个方法,同时引发一个事件,老鼠作为事件的处理者,它的处理结果是听到猫叫就逃跑,这样定义一个委托就是表示老鼠对猫的动静的监听。
简单实现代码如下:
None.gifusing System; None.gifusing System.Collections.Generic; None.gifusing System.Text; None.gifnamespace TestConsole ExpandedBlockStart.gif{ InBlock.gif// 定义一个委托,用来表示老鼠监听着猫的动静 InBlock.gifpublicdelegatevoid CatListeningHandler(); InBlock.gif InBlock.gifpublicclass Cat ExpandedSubBlockStart.gif{ InBlock.gif//定义一个事件,这个事件表示猫叫了 InBlock.gifpublicevent CatListeningHandler CatCry; InBlock.gif InBlock.gifpublicvoid Cry() ExpandedSubBlockStart.gif{ InBlock.gif Console.WriteLine("Meow~~"); InBlock.gif OnCry(); ExpandedSubBlockEnd.gif } InBlock.gif InBlock.gifprotectedvirtualvoid OnCry() ExpandedSubBlockStart.gif{ InBlock.gifif (CatCry !=null) ExpandedSubBlockStart.gif{ InBlock.gif CatCry(); ExpandedSubBlockEnd.gif } ExpandedSubBlockEnd.gif } ExpandedSubBlockEnd.gif } InBlock.gif InBlock.gifpublicclass Mouse ExpandedSubBlockStart.gif{ InBlock.gifpublicvoid Run() ExpandedSubBlockStart.gif{ InBlock.gif Console.WriteLine("Mouse run awaydot.gif"); ExpandedSubBlockEnd.gif } ExpandedSubBlockEnd.gif } InBlock.gif InBlock.gifclass Program ExpandedSubBlockStart.gif{ InBlock.gifstaticvoid Main(string[] args) ExpandedSubBlockStart.gif{ InBlock.gif Cat cat =new Cat(); InBlock.gif InBlock.gif Mouse mouse =new Mouse(); InBlock.gif InBlock.gif// 把猫叫和老鼠逃跑联系起来 InBlock.gif cat.CatCry +=new CatListeningHandler(mouse.Run); InBlock.gif InBlock.gif cat.Cry(); ExpandedSubBlockEnd.gif } ExpandedSubBlockEnd.gif } ExpandedBlockEnd.gif} None.gif |
小结:cat.CatCry +=new CatListeningHandler(mouse.Run)中CatListenningHandler是一个委托,它接收一个无参无返回值的方法名作为参数,CatCry是该委托的事件实例用+=操作符把委托挂接到事件,简单的说就是当触发CatCry事件的时候,方面mouse.Run()就会执行。事件实例CatCry可以用+=链接多个委托实例,而后触发事件时多个链接的委托方法会按序执行。如委托链中有不需要的委托,可用-=操作符移除。