查看委托的IL

通过IL来查看委托的原理,

委托示例代码

写一个委托的类如下

using System;
 
namespace MyCollection
{
    //定义一个类,该类包含两个静态方法
    class IntOperations 
    {
        //求整数的倍数
        public void Twice(int num) 
        {
            Console.WriteLine("整数{0}的倍数是 {1}", num, num * 2);
        }
        //求整数的平方
        public static void Square(int num) 
        {
            Console.WriteLine("整数{0}的平方是 {1}\n", num, num * num);
        }
    }
 
    delegate void IntOp(int x); //定义一个委托
 
    public class DelegateExample
    {
        static void Main(string[] args)
        {
            //实例化一个IntOperations对象
            IntOperations mo = new IntOperations();
            //创建Twice方法的委托对象
            IntOp operations = new IntOp(mo.Twice);
            //创建并增加Square方法的委托对象
            operations += new IntOp(IntOperations.Square);
            
            operations(5);
            operations(8);
            //创建并移除Square方法的委托对象
            operations -= new IntOp(IntOperations.Square);
            operations(5);
            operations(8);
            Console.WriteLine("按任意键退出...");
            Console.ReadLine(); //让屏幕暂停,以方便观察结果
        }
    }
}

相关文章:

  • 2022-01-20
  • 2022-12-23
  • 2022-12-23
  • 2021-10-12
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-11-19
  • 2021-09-03
  • 2021-09-07
  • 2021-11-24
相关资源
相似解决方案