zoukankan      html  css  js  c++  java
  • .net知识和学习方法系列(二十)CLR委托

    delegate void DL(int i);

    上面是一个委托的定义,委托向外提供了一种回调函数的机制,在.net中的委托是类型安全的,一个委托能实现对一类方法的回调,这个统一是通过委托的参数和返回值来实现的。

    上面代码如果用IL来解释,是这个样子

     

     

    如果用C#来表示,一个委托就成了下面的代码

      class DL:System .MulticastDelegate

       {

           public DL(Object object,IntPtr method);

           public virtual void Invoke(Int32 i);

           public virtual IAsyncResult BeginInvoke(Int32 i,AsyncCallback callback,Object object);

           public virtual void EndInvoke(IAsyncResult result);    

       }

    当然,上面代码是通不过编译的,只是对应IL代码的表现。

    在上面的类中,有一个构造函数,和三个方法,同时还有三个继承至MulticastDelegate的三个非公有字段_target,_methodPtr,_invocationList。

    在构造函数中有两个参数,第一个是object类型,这里指的是被回调方法的对象,如果该方法是静态的,那么这个值就是null,第二个参数是个IntPtr,这个参数是回调方法。并且在构造器中,会把object赋给_target,IntPtr赋给_methodPtr来保存。

    另外一个字段_invocationList是一个存放回调方法的链表。

    static void Main(string[] args)

            {

                Program p = new Program();

                DL dl = new DL(p.FF);

                dl += p.FF;

                dl += FF1;

                dl(1);

            }

            public static void FF1(int i)

            {

                Console.WriteLine("d");

            }

            public void FF(int i)

            {

                Console.WriteLine(DateTime .Now .ToString ());

            }

    上面代码的+=的过程,其实就是向_invocationList添加委托的过程。

    还有代码中,我们调用了dl(1),这个代码其实是dl.Invoke(1)。

    后两个方法的使用,可参看http://www.cnblogs.com/axzxs2001/archive/2008/04/17/1157269.html

  • 相关阅读:
    php 显示文件 与Windows文件名排序一致
    pip3 install uwsgi 报错
    centos7 安装mysql 5.7
    Win7 开始菜单搜索添加快捷方式
    centos7.7 clamav 查杀病毒
    CentOS7.x 默认php版本与php7.4共存
    centos6.5 yum安装redis
    centos6 yum安装mysql 5.6 (完整版)
    解决phpmyadmin出现: Maximum execution time of 300
    Castle Windsor 使MVC Controller能够使用依赖注入
  • 原文地址:https://www.cnblogs.com/axzxs2001/p/1301968.html
Copyright © 2011-2022 走看看