一、委托介绍
委托从字面上理解就是一种代理,类似于房屋中介,由租房人委托中介帮其租赁房屋。
在C#语言中,委托则是委托某个方法来实现具体的功能。
委托的特点:
- 委托是一种引用类型,虽然在定义委托时与方法有些相似,但不能将其称为方法。
- 从数据结构来讲,委托是和类一样是一种用户自定义类型。
- 委托是方法的抽象,它存储的就是一系列具有相同签名和返回类型的方法的地址。
- 调用委托的时候,委托包含 的所有方法将被执行。
委托的分类:
- 方法委托
- 多播委托
- 匿名委托
委托的使用步骤:
- 定义声明委托
- 实例化委托
- 调用委托
二、方法委托
方法委托是最常用的一种委托,定义的语法形式:
修饰符 delegate 返回值类型 委托名(参数列表);
一个方法委托例子:
先写一个方法,给委托调用。
public void Consloe(string god)
{
Console.WriteLine(god);
}
class Program
{
public delegate void Cols(string god);
static void Main(string[] args)
{
Student std=new Student(1,”张三”,18);
Cols tag=new Cols(std.Console);
tag(“方法委托”);
}
}
三、多播委托
在C#语言中多播委托是指在一个委托中注册多个方法,在注册方法时可以在委托中使用加号运算符或者减号运算符来实现添加或撤销方法。
class Program
{
public delegate void Cols(string god);
static void Main(string[] args)
{
Student std=new Student(1,”张三”,18);
Student std1=new Student(2,”张云”,17);
Student std2=new Student(3,”张原”,16);
Cols tag=new Cols(std.Console);
tag+=std1.Console;
tag+=std2.Console;
//tag-=std2.Console; 去除委托方法
tag(“多播委托”);
}
}
四、匿名委托
在C#语言中匿名委托是指使用匿名方法注册在委托上,实际上是在委托中通过定义代码块来实现委托的作用。
语法形式:
//定义委托
修饰符 delegate 返回值类型 委托名(参数列表);
//定义匿名委托
委托名 委托对象=delegate
{
//代码块
}
委托对象名(参数列表); //调用匿名委托
class Program
{
public delegate void Cols(string god);
static void Main(string[] args) {
Student std=new Student(1,”张三”,18);
Cols tag=new Cols(std.Console);
tag=delegate(string god){
Console.WriteLine(god);
Console.Write(std);
};
tag(“匿名委托”);
}
}