委托 三步即可实现

委托是C#里非常重要的应用。其实只要简单的三步就能用委托。编辑时间:20181229

  1. 声明委托
  2. 委托一样格式的方法
  3. 实例化委托
        delegate int MyDelegete(int n);//一、声明委托

        static int num = 10;
        public static int Add(int n)//二、跟委托同样格式的方法
        {
           return  num += n;
        }
        public static int Mul(int n)//二、跟委托同样格式的方法
        {
            return num *= n;
        }
        public static int GetNum()
        {
            return num;
        }

        private static void UseDelegateMethod(MyDelegete d)
        {
            d(10);
        }

        static void Main(string[] args)
        {
            MyDelegete d1 = new MyDelegete(Add);//三、声明委托
            MyDelegete d2 = new MyDelegete(Mul);
            d1(25); Console.WriteLine(GetNum());
            d2(5); Console.WriteLine(GetNum());
            MyDelegete d; d = d1;d += d2; //多播委托
            d(10); Console.WriteLine(GetNum());
            UseDelegateMethod(d1); Console.WriteLine(GetNum());//系数相同,用方法传委托对象
            UseDelegateMethod(d2); Console.WriteLine(GetNum());
            Console.ReadKey();
        }

图片版本代码:


委托.png
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容