C#_委托的使用

来源:互联网 发布:晋城监狱网络改造 编辑:程序博客网 时间:2024/05/02 04:23
    // 委托其实就是一种数据类型    delegate void behaviourDelegate();    class Person    {        public void sayDelegate()        {            Console.WriteLine("sayDelegate");        }        public void talkDelegate()        {            Console.WriteLine("talkDelegate");        }        public void walkDelegate()        {            Console.WriteLine("walkDelegate");        }    }    class Start    {        static void Main(string[] args)        {            var per = new Person();            // 初始化单一委托            behaviourDelegate del1 = new behaviourDelegate(per.sayDelegate);            del1();            // 初始化多播委托            behaviourDelegate del2 = null;            del2 += per.sayDelegate;            del2 += per.talkDelegate;            del2 += per.walkDelegate;            del2();            Console.ReadLine();        }    }
using System;using System.Collections;using System.Collections.Generic;using System.IO;using System.Linq;using System.Text;namespace CShapeTest{    class Start    {        // 没有参数,没有返回值        static void PrintStr()        {            Console.WriteLine("PrintStr");        }        // 有一个参数或者多个参数,没有返回值        static void PrintInt(int a, int b)        {            Console.WriteLine(a + b);        }        static void Main(string[] args)        {            // 系统内置委托类型Action            //Action a = new Action(PrintStr);            //a();//常用调用方式            //a.Invoke();//不常用调用方式            // Action最多只能有16个参数            Action<int, int> a = new Action<int, int>(PrintInt);            a(1, 2);            Console.ReadLine();        }    }}
using System;using System.Collections;using System.Collections.Generic;using System.IO;using System.Linq;using System.Text;namespace CShapeTest{    class Start    {        // 没有参数,返回值        static string PrintStr()        {            return "Hello world";        }        // 有一个参数或者多个参数,有返回值        static int PrintInt(int a, int b)        {            return a + b;        }        static void Main(string[] args)        {            // 系统内置委托类型Func,Func一定有返回值            //Func<string> func = new Func<string>(PrintStr);            //Console.WriteLine(func());            Func<int, int, int> func = new Func<int, int, int>(PrintInt);            Console.WriteLine(func(1, 5));            Console.ReadLine();        }    }}



0 0
原创粉丝点击