C#学习之委托与事件

委托

语法:  public  delegate void MyDelegate();

使用:  1.定义委托----public  delegate void MyDelegate();

          2.注册委托挂载方法 ----1)  类名.MyDelegate myDelegate = new 类名.MyDelegate();//实例化委托   可以用类名直接访问委托

                                           myDelegate += FunctionA;  //注册委托(挂载方法)    

                                  或总写 :  类名.MyDelegate myDelegate += new 类名.MyDelegate(FunctionA);

                                         2) 实例化委托所在类   类名  myTest = new 类名();

                                            myTest.myDel +=FunctionA;//myDel为类下的一个委托实例

          3.调用    myDelegate();

 

 

 

事件

语法:  public delegate void MyDelegate();

          public event MyDelegate myDelegateEvent;

使用: 1.定义事件  ---public event MyDelegate myDelegateEvent;

         2.事件的触发机制(必须和事件在同一个类中) 外界无法直接用EventMyDel()来触发事件---public void TouchEvent(){ myDelegate();}

         3.注册事件(挂载方法)---myTest.myDelegateEvent += FunctionA;

         4.调用  myTest.TouchEvent();

 

 

 

注:委托和事件的区别---委托注册方法可使用+=、=、-= ;而事件注册只能使用+=、-=。

 

以上代表个人对委托和事件学习后的总结。

http://www.cnblogs.com/holyknight-zld/archive/2012/08/30/delegateEvent.html该博文写得很详细。

 

posted on 2015-09-22 15:26  &木子  阅读(148)  评论(0编辑  收藏  举报

导航