委托
委托是方法的抽象,它存储的就是一系列具有相同签名和返回类型的方法的地址。调用委托的时候,委托包含的所有方法将被执行。
委托是类型,就好像类是类型一样。与类一样,委托类型必须在被用来创建变量以及类型对象之前声明。
委托的声明原型是
delegate <函数返回类型> <委托名> (<函数参数>)
本身自带的委托## Action
Action是无返回值的泛型委托。
Action 表示无参,无返回值的委托
Action<int,string> 表示有传入参数int,string无返回值的委托
Action<int,string,bool> 表示有传入参数int,string,bool无返回值的委托
Action<int,int,int,int> 表示有传入4个int型参数,无返回值的委托
Action至少0个参数,至多16个参数,无返回值。
## Func
Func是有返回值的泛型委托
Func<int> 表示无参,返回值为int的委托
Func<object,string,int> 表示传入参数为object, string 返回值为int的委托
Func<object,string,int> 表示传入参数为object, string 返回值为int的委托
Func<T1,T2,,T3,int> 表示传入参数为T1,T2,,T3(泛型)返回值为int的委托
Func至少0个参数,至多16个参数,根据返回值泛型返回。必须有返回值,不可void
例:
创建一个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));
}
}
}
多播委托
每个委托都只包含一个方法调用,调用委托的次数与调用方法的次数相同。如果调用多个方法,就需要多次显示调用这个委托。当然委托也可以包含多个方法,这种委托称为多播委托。
当调用多播委托时,它连续调用每个方法。在调用过程中,委托必须为同类型,返回类型一般为void,这样才能将委托的单个实例合并为一个多播委托。如果委托具有返回值和/或输出参数,它将返回最后调用的方法的返回值和参数。(有些书上和博客说多播委托返回类型必须为void,并且不能带输出参数,只能带引用参数,是错误的)。
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 + "心之所向即安然");
}
}
}