一、什么是委托
委托可以理解为对函数进行了一层包装(封装),原本让函数做的事,可以交给委托,然后 委托 再转给函数。
这么做的意义何在?(感觉更麻烦了有木有)
非也,委托使得c#中的函数可以作为参数来被传递(作用相当于c++的函数指针)。
上代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
//1.定义委托
delegate void MyDelegate(int para1, int para2);
static void Main(string[] args)
{
//2.声明委托
MyDelegate d;
//3.实例化委托
d = new MyDelegate(Program.Add);
//4.委托类型作为参数传递
MyMethod(d);
Console.Read();
}
//方法定义必须和委托定义相同包括:参数类型数量,返回值
private static void Add(int para1, int para2)
{
int sum = para1 + para2;
Console.WriteLine("两个数的和为" + sum);
}
//方法参数是委托类型
private static void MyMethod(MyDelegate mydelegate)
{
//5.在方法中调用委托
mydelegate(3, 4);
//直接调用方法(与用委托在本例中的效果一样)
Add(3, 4);
}
}
}
二、委托的目的与本质
目的:使得一个方法可以作为另一个方法的参数进行传递
本质:委托的本质是类。调用委托的本质是调用实例化委托对象中的Invoke方法
三、委托链
连接多个方法封装的委托叫做委托链,又称多路广播委托
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
//声明一个委托类型
public delegate void DelegateTest();
static void Main(string[] args)
{
//用静态方法来实例化委托
DelegateTest dtstatic = new DelegateTest(Program.method1);
//用实例方法来实例化委托
DelegateTest dtinstance = new DelegateTest(new Program().method2);
//定义一个委托对象,一开始初始化null.
DelegateTest delegatechain = null;
//使用“+”符号链接委托,链接多个委托后即形成委托链
delegatechain += dtinstance;
delegatechain += dtstatic;
//调研委托链
delegatechain();
Console.WriteLine("第二次调用委托链");
//干掉了实例方法
delegatechain -= dtinstance;
delegatechain();
Console.Read();
}
//静态方法
private static void method1()
{
Console.WriteLine("我是静态方法");
}
private void method2()
{
Console.WriteLine("我是动态方法");
}
}
}