委托

委托是方法的抽象,它存储的就是一系列具有相同签名和返回类型的方法的地址。调用委托的时候,委托包含的所有方法将被执行。
委托是类型,就好像类是类型一样。与类一样,委托类型必须在被用来创建变量以及类型对象之前声明。
委托的声明原型是
delegate <函数返回类型> <委托名> (<函数参数>)
例:
创建一个people类定义两个方法

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _02委托
{
    class People
    {
        public string Talk()
        {
            return "张三";
        }
        public int Add(int a,int b)
        {
            return a + b;
        }
    }
}

program类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _02委托
{
    class Program
    {
    //委托
        delegate string DelTalk();
        delegate int Deladd(int a,int b);
        static void Main(string[] args)
        {
            Console.WriteLine("进来一个人");
            People p = new People();
            Setname(p.Talk);
            setnum(p.Add);
            Console.ReadLine();
        }
        static void  Setname(DelTalk talk)
        {
            Console.WriteLine("这个人的姓名是:" + talk());
        }
        static void setnum(Deladd Add)
        {
            Console.WriteLine("这两个数之和是:" + Add(4,5));
        }
    }
}

多播委托

每个委托都只包含一个方法调用,调用委托的次数与调用方法的次数相同。如果调用多个方法,就需要多次显示调用这个委托。当然委托也可以包含多个方法,这种委托称为多播委托。
例:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _03委托2
{
    class Program
    {
        static void Main(string[] args)
        {
            Action action = Run;
            action();
            Action<string, int> active = Runs;
            active("小明", 50);
            Func<string, int, string> func = Tall;
            Console.WriteLine(func("小明", 28));
            //多播委托
            Action<string> actiew = Fun1;
            actiew += Fun2;
            if (actiew!=null)
            {
                actiew("清");
            }
            actiew -= Fun1;
            if (actiew!=null)
            {
                actiew("清清");
            }
            Console.ReadLine();
        }
        static void Run()
        {
            Console.WriteLine("奔跑");
        }
        static void  Runs(string name,int longs)
        {
            Console.WriteLine(name + "跑了" + longs + "米");
        }
        static string Tall(string name,int ages)
        {
            return name + "今年" + ages + "岁";
        }
        //多播委托
        static void Fun1(string name)
        {
            Console.WriteLine(name + "好好学习,天天向上");
        }
        static void Fun2(string name)
        {
            Console.WriteLine(name + "只要你乖给你买条gai(街)");
        }
    }
}
posted on 2019-02-06 15:26  豆皮没有豆  阅读(101)  评论(0)    收藏  举报