委托可以说是c#最常用的,非非非常重要,下面带大家快速入门委托
1.委托是什么?
委托是一个引用类型,他保存方法的指针,指向方法,当我们调用委托时,其指向的方法被执行。
(人话就是委托就是方法的代表,执行委托就是执行委托代表的方法)
2.委托能干什么?
用于统一调用方法,一个委托可以调用多个方法
3.委托怎么用
1.定义委托
定义委托时用deleagte关键字,返回值类型和入参要和所关联方法的返回值类型和入参一样
delegate 返回值类型 委托名(入参);
2.创建委托变量
3.委托变量关联方法
4.执行委托
下面是一个最简单的使用:
//1.委托声明
delegate int NumberChange(int p);
-----------------------------------------------------------------------
//方法
public int Add(int a)
{
a++;
return a;
}
-------------------------------------------------------------------------
//委托里面的方法入参类型和返回值类型要和委托声明的入参类型和返回值类型一样。
void static main()
{
NumberChange nc = new NumberChange(Add);//2-3.创建委托变量并关联方法
int num = nc(5);//4.调用委托指定的方法
Console.WriteLine(num);
}
4.泛型委托
自定泛型委托和普通委托使用差不多,这里介绍平时经常是同的微软官方封装好的两种委托
1.不带返回值的——Action
2.带返回值的——Func
具体使用直接看代码和注释
/*官方给出两种,一中是不带返回值的(Action),
另一种带返回值的(Func),底层大量使用重载,最多16个泛型入参*/
//方法
static void eat()
{
Console.WriteLine("我要吃汉堡包");
}
//没有返回值的
Action<string> action = new Action<string>();
Action<string> a = eat;//省略写法
//前面的string是方法的入参类型,追后一个是是返回值类型
Func<string,string> func = new Func<string,string>();
5.多播委托
是什么?
就是一个委托变量关联多个方法,执行委托直接执行多个方法
//原始写法,把指向方法1,方法2,方法3的三个委托连起来
Action a = new Action(Method1);
a = (Action)MulticastDelegate.Combine(a,new Action(Method2));//关联Method2
a = (Action)MulticastDelegate.Comblie(a,new Action(Method3));//关联Method3
a = (Action)MulticastDelegate.Remove(a,new Action(Method2));//去掉Method2
a();
//委托配合lamda表达式的省略写法
Funk<string> funk = ()=>{return "Hello World"};
funk+=()=>{return "1"};
funk+=()=>{return "2"};
funk+=()=>{return "3"};
funk();
多播委托的注意事项
每个委托都继承自MulticastDelegate,所以每个委托都是多播委托 |
带返回值的多播委托,只返回最后一个方法的返回值 |
多播委托可以用+=和-=简化书写 |
使用lamda表达式不能使用-=简略写法(即给委托传递两个相同的方法,因为没有方法名,委托会认为是两个方法) |
觉得有帮助给博主点个关注,欢迎交流,共同进步