文档详情

第4章 面向对象技术.ppt

发布:2017-07-17约3.22万字共113页下载文档
文本预览下载声明
4.8 委托与事件 (3)定义一个委托类型的实例变量(委托对象),让该实例变量指向某一个要调用具体的方法。其一般格式如下。 MyDelegate d1 = new MyDelegate(delegateMethod1); (4)通过委托对象调用调用委托类型变量指向的方法。其一般格式如下。 d1(hello); //实际上是执行delegateMethod1方法的程序代码段。 委托类型名 委托对象名=new 委托类型名(要调用方法名); 委托对象名(实参列表); 4.8 委托与事件 delegate void MyDelegate(string input); //定义委托 //定义所要调用的方法 void delegateMethod1(string input){ Console.WriteLine(This is delegateMethod1 and the input is {0},input);} //定义一个委托类型的实例变量 MyDelegate d1 = new MyDelegate(delegateMethod1); d1(hello);//实际上是执行delegateMethod1方法的程序代码段。 class A { public static void Hello(string input) { Console.WriteLine(This is delegateMethod1 and the input is {0},input); } public static void Hello2(string input) { Console.WriteLine(This is Hello2 and the input is {0}, input); } } class Program { delegate void MyDelegate(string input);//声明一个委托类型 static void Main(string[] args) { MyDelegate d; d = new MyDelegate(A.Hello); d(china); A.Hello(china); d = new MyDelegate(A.Hello2); d(china); } } } 4.6 委托与事件 2.委托对象调用多个方法 委托对象可以调用多个方法,这些方法的集合称为调用列表。 委托使用“+”、“-”、“+=”和“-=”等运算符向调用列表中增加或移除事件处理方法。 d += new MyDelegate(A.Hello2); 4.8 委托与事件 4.8.2 事件 事件有很多,比如说鼠标的事件:MouserMove,MouserDown等,键盘的事件:KeyUp,KeyDown,KeyPress。有事件,就会有对事件进行处理的方法,而事件和处理方法之间是怎么联系起来的呢?委托就是他们中间的桥梁,事件发生时,委托会知道,然后将事件传递给处理方法,处理方法进行相应处理。 1.为事件创建一个委托类型 所有事件是通过委托来激活的,其返回值类型一般为void型。为事件创建一个委托类型的语法格式如下: delegate void 委托类型名([触发事件的对象名,事件参数]); delegate void MyEventHandler(object sender , EventArgs e); 触发该事件的对象 事件处理函数中用到的数据 4.8 委托与事件 2.事件的声明 定义格式如下: 例如: 访问修饰符 event 委托类型 事件名; public event MyEventHandler MyEvent; 4.8 委托与事件 public class EventClass { public delegate void CustomEventHandler(object sender, EventArgs e)? public event CustomEventHandler CustomEvent? public void InvokeEvent() { if (CustomEvent != null) //判断事件与事件处理方法是否
显示全部
相似文档