委托系列02-委托的实例化及执行

一、代码准备

    /// <summary>
    /// 1.无参数无返回值委托
    /// </summary>
    public delegate void NoReturnNoParaOutClass();
    public class CustomDelegate //: MulticastDelegate
    {
        /// <summary>
        /// 2.无参数无返回值委托
        /// </summary>
        public delegate void NoReturnNoPara();

        /// <summary>
        /// 3.有参数无返回值委托
        /// </summary>
        /// <param name="x"></param>
        /// <param name="y"></param>
        public delegate void NoReturnWithPara(int x, int y);

        /// <summary>
        /// 4.无参数有返回值的委托
        /// </summary>
        /// <returns></returns>
        public delegate int WithReturnNoPara();

        /// <summary>
        /// 5.带参数,带返回值的委托
        /// </summary>
        /// <param name="x"></param>
        /// <param name="y"></param>
        /// <returns></returns>
        public delegate int WithReturnWithPara(out int x, ref int y);

        public static void Show()
        {

            NoReturnNoParaOutClass noReturnNoParaOutClass = new NoReturnNoParaOutClass(NoReturnNoParaMehtod);

            //NoReturnNoParaOutClass noReturnNoParaOutClass1 = new NoReturnNoParaOutClass(NoReturnWithParaMehtod);
            //NoReturnNoPara noReturnNoPara = new NoReturnNoPara(NoReturnWithParaMehtod);
            //NoReturnWithPara noReturnWithPara = new NoReturnWithPara(NoReturnNoParaMehtod);
            NoReturnWithPara noReturnWithPara1 = new NoReturnWithPara(NoReturnWithParaMehtod);
            //noReturnWithPara1.Invoke()
            //WithReturnNoPara withReturnNoPara = new WithReturnNoPara(WithReturnNoParaMehtod);



             WithReturnNoPara withReturnNoPara = WithReturnNoParaMehtod; //这样写也没有问题---委托的实例--可以直接指向一个和这个委托参数+返回值完全匹配的方法;--语法糖--编译器给我们提供额便捷功能--new WithReturnNoPara();省略掉了

            int iResult = withReturnNoPara.Invoke();//如果委托定义没有参数;在Inovke也没有参数 
            //withReturnNoPara.BeginInvoke(null, null);//开启一个新的线程去执行委托
            //withReturnNoPara.EndInvoke()//回调


            NoReturnWithPara noReturnWithPara2 = NoReturnWithParaMehtod;
            NoReturnWithPara noReturnWithPara3 = (x, y) => { };
        }

        private static void NoReturnNoParaMehtod()
        {
            Console.WriteLine("这是一个无参数无返回值的方法。。。");
        }

        private static void NoReturnWithParaMehtod(int x, int y)
        {
            Console.WriteLine($"这是一个带参数无返回值的方法。。。");
        }

        private static int WithReturnNoParaMehtod()
        {
            Console.WriteLine($"这是一个无参数带返回值的方法。。。");
            return default(int);
        }

        private static int WithReturnWithParaMehtod(out int x, ref int y)
        {
            Console.WriteLine($"这是一个带参数无返回值的方法。。。");
            x = 1;
            return default(int);
        }
    }

二、委托的实例化

委托系列02-委托的实例化及执行

从上图得知,委托实例化是传递的函数,且函数必须与委托声明一致。(返回值、参数)

三、委托的执行

委托系列02-委托的实例化及执行

上一篇:【算法导论】桶排序


下一篇:02-脚手架架构设计和框架搭建