委托:可以理解为装载方法的容器,可以转载方法的指针
namespace 委托 { class Program { static void Main(string[] args) { //第一版:原始委托 Main1 m = new Main1(); m.Run(); //第二版:委托参数版 m.RunHandler(x=> { Console.WriteLine(x + "+rum"); },"王五"); //第三版:Action实现委托 m.Handle(x => { Console.WriteLine(x + "无返回值"); },"赵六"); //第三版:Func实现委托 string res = m.Handle(x => x + "func有返回值", "田七"); Console.WriteLine(res); Console.ReadKey(); } } } namespace 委托 { public class Main1 { public delegate void HandlerEven(string name); /* * 委托转载方法的容器,定义好方法的入参和返回值 * 第一版:原始委托 */ public void Run() { HandlerEven say1 = Say; HandlerEven say2 = new HandlerEven(Say); say2 += Say2; say1("张三"); say2("李四"); } public void Say(string name) { Console.WriteLine("run+" + name); } public void Say2(string name) { Console.WriteLine("run2+" + name); } /* * 第二版:委托参数版 */ public void RunHandler(HandlerEven say,string name) { say(name); } /* * 第三版:微软内置委托Action:无返回值 Func:有一个返回值 */ public void Handle(Action<string> action,string name) { action(name); } public string Handle(Func<string,string>fun ,string name) { return fun(name); } } }
委托实现观察者模式:
public class Delegates { public delegate void HandlerEven(string name); public void Run() { HandlerEven say = CatSay; say += MouseRun; say += Sleep; say("叫"); } public void CatSay(string name) { Console.WriteLine("猫叫了:" + name); } public void MouseRun(string name) { Console.WriteLine("吓跑了老鼠:" + name); } public void Sleep(string name) { Console.WriteLine("惊醒了主人:" + name); } public void SecondRun() { List<Action<string>> list = new List<Action<string>>(); list.Add(CatSay); list.Add(MouseRun); list.Add(Sleep); foreach (var item in list) { item("second"); } } public void Handle(Action<string> action, string name) { action(name); } }
主代码调用:
class Program { static void Main(string[] args) { Delegates de = new Delegates(); de.Run(); de.SecondRun(); Console.ReadKey(); } }