C Sharp 委托方法

版权声明:原创笔记 ----黑暗灵魂 https://blog.csdn.net/qq_38843118/article/details/89634474

        //定义一个委托类型
        public delegate void Methodv();
        public delegate string Methods(int para1,string para2);
        //一个普通方法
        public static void OnMethodv()
        {
            Console.WriteLine("On Method v");
        }
        public static string OnMethods(int i,string s)
        {
            Console.WriteLine("On Method s");
            return "";
        }
        public static void OnMethodf(int i, string s, float f)
        {
            Console.WriteLine("On Method f");
        }
        public static bool OnMethodb(int i, string s, float f)
        {
            Console.WriteLine("On Method b");
            return true;
        }

        static void Main(string[] args)
        {
            //使用委托类型创建实例(委托的参数,返回值必须和赋值的普通方法的一致)
            Methodv mv = new Methodv(OnMethodv);
            Methods ms = OnMethods;        
            //通过委托调用普通方法
            mv();                   //输出 On Method v
            ms.Invoke(12, "Black"); //输出 On Method s

            //系统内置委托 Action: 没有返回值,最多可以有16个参数
            Action cv = OnMethodv;
            Action<int, string, float> cs = OnMethodf;
            cv();                   //输出 On Method v
            cs(8, "Black", 1.6f);   //输出 On Method f

            //系统内置委托 Func: 有返回值(最后一个泛型),最多可以有16个参数
            Func<int, string, float, bool> fb = OnMethodb;  //返回值bool 参数int,string,float
            bool res = fb.Invoke(9, "Black", 1.2f);         //输出 On Method b

            Console.ReadKey();
        }

猜你喜欢

转载自blog.csdn.net/qq_38843118/article/details/89634474
今日推荐