public delegate void ConsoleWriteStr(string name,DateTime now);
public delegate int DelegateAdd(int x, int y);
//第一步 使用匿名函数 ConsoleWriteStr cws1= new ConsoleWriteStr( delegate(string name, DateTime now){ Console.WriteLine("我叫{0},我喜欢学习{1}", name, now); } );
//第二步将delegate换成=> , =>的左边是参数列表,右边是函数体 ConsoleWriteStr cws2 = (string name, DateTime now) => { Console.WriteLine("我叫{0},我喜欢学习{1}", name, now); };
//第三步去掉操作类型,原因是委托要求与方法签名一致 ConsoleWriteStr cws3 = ( name, now) => { Console.WriteLine("我叫{0},我喜欢学习{1}", name, now); };
//第三步去掉方法体的大括号,如果方法体只有一行,可以将大括号去掉 ConsoleWriteStr cws4 = (name, now) => Console.WriteLine("我叫{0},我喜欢学习{1}", name, now);
DelegateAdd func = (x, y) => { return x + y; }; DelegateAdd func1 = (x, y) => x + y;
//系统自带的委托Action,该委托不带返回值 Action ac1 = () => { }; //无参数无返回值 Action<string> ac2 = x =>{ }; //泛型委托 一个参数可以去掉小括号 Action<string> ac3 = x => { }; //泛型委托 Action<string,int,DateTime,Action> ac4 = (x, y, z, a) => { }; //泛型委托
//系统自带的委托Func,该委托带有返回值,最多16个参数,最后一个参数为返回值 Func<string> fun1 = () => " "; Func<DateTime> fun2 = () => DateTime.Now; Func<string, double,long, int> fun3 = (s,l, d) => { return 1+l; };