zoukankan      html  css  js  c++  java
  • 事件与委托

    事件是构建在委托上的,例如定义Button的Click事件:
          public event EventHandler Click
    需要event关键字和EventHandler委托,EventHandler在这里的作用就好像接口,所有想接收事件通知的实例必须实现符合EventHandler参数定义和返回值定义的回调函数,.NET框架通过委托这种方式保证了回调函数类型的安全。
    再来看委托的定义,以EventHandler为例:
    public delegate void EventHandler(object sender, EventArgs e);
    很像方法的定义,只是多了一个delegate关键字;不过它实际上是一个类,可以查看IL代码:

    .class public auto ansi serializable sealed EventHandler
        extends System.MulticastDelegate
    {
        .custom instance 
    void System.Runtime.InteropServices.ComVisibleAttribute::.ctor(bool= bool(true) }
        .method 
    public hidebysig specialname rtspecialname instance void .ctor(object 'object', native int 'method') runtime managed
        
    {
        }


        .method 
    public hidebysig newslot virtual instance class System.IAsyncResult BeginInvoke(object sender, class System.EventArgs e, class System.AsyncCallback callback, object 'object') runtime managed
        
    {
        }


        .method 
    public hidebysig newslot virtual instance void EndInvoke(class System.IAsyncResult result) runtime managed
        
    {
        }


        .method 
    public hidebysig newslot virtual instance void Invoke(object sender, class System.EventArgs e) runtime managed
        
    {
        }


    }


    类中除了构造函数还有三个方法,构造函数接收接收两个参数,一个对象引用和一个指向回调函数的整数,在运行时,EventHandler通过Invoke方法找到对应对象的对应方法(也就是回调函数)执行具体操作。(EventHandler继承自System.MulticastDelegate,在李建忠译的框架程序设计那本书中说MulticastDelegate中含有一个_prev字段使委托可以构成链表实现多播,不过在.NET2.0中查看代码没有看到,也没有详细研究,不过这本书里把.NET1.1中的事件和委托讲的非常透彻,极力推荐)

  • 相关阅读:
    SDNU 1219.sign up problem
    SDNU 1232.A*B Problem(高精度)
    Go操作MySQL
    BootStrap jQuery 在线cdn
    Go语言标准库之http/template
    Go语言基础之net/http
    Go语言基础之网络编程
    Go语言基础之单元测试
    Go语言基础之rand(随机数)包
    Go语言基础之并发
  • 原文地址:https://www.cnblogs.com/end/p/750363.html
Copyright © 2011-2022 走看看