什么是委托?
可以把委托看成是用来执行方法(函数)的一个“指针” 通俗的说就是:通过委托,我们可以把方法当成参数传递。
示例
举个例子:“设想,如果我们写了一个厨师做菜的方法,里面有拿菜、切菜、配菜、炒菜四个步骤,但编写此方法代码的人想让配菜这个环节让调用方法的人来实现,换句话说,就是想把方法作为参数来传递,那么怎么来实现呢?
拿菜、切菜、配菜、炒菜我们定义4个方法,抽象成一个做菜类(ZuoCai.cs)。
ZuoCai zuoCai = new ZuoCai();
ZuoCai.ZuoCaiDelegate zuoCaiDelegate = new ZuoCai.ZuoCaiDelegate(zuoCai.NaCai);
zuoCaiDelegate += zuoCai.QieCai;
zuoCaiDelegate += zuoCai.PeiCaiJiaLa;
zuoCaiDelegate += zuoCai.ChaoCai;
zuoCai.StartZuoCai(zuoCaiDelegate);
public class ZuoCai
{
public delegate void ZuoCaiDelegate();
public void NaCai()
{
Console.WriteLine("A负责拿菜!");
}
public void QieCai()
{
Console.WriteLine("B负责切菜!");
}
public void PeiCai()
{
Console.WriteLine("C负责配菜!");
}
public void PeiCaiJiaLa() { Console.WriteLine("C负责配菜,要求多放点辣椒!"); }
public void ChaoCai()
{
Console.WriteLine("D负责炒菜!");
}
/// <summary>
/// 开始做菜的方法
/// </summary>
/// <param name="zuoCaiDelegate"></param>
public void StartZuoCai(ZuoCaiDelegate zuoCaiDelegate)
{
zuoCaiDelegate();
}
}
原文:https://blog.csdn.net/qq_36330228/article/details/107449807?ops_request_misc=&request_id=5aecec1f548948f6a6cd3e2f94161f08&biz_id=&utm_medium=distribute.pc_search_result.none-task-blog-2~blog~koosearch~default-1-107449807-null-null.268^v1^control&utm_term=Delegate&spm=1018.2226.3001.4450
标签:zuoCaiDelegate,委托,ZuoCai,C#,void,zuoCai,Delegate,配菜,public From: https://www.cnblogs.com/KevinSteven/p/17475021.html