经过一段时间的学习,想写个博客记录一下委托、lambda的学习理解过程,方便自己可以回忆知识点。如果有地方有问题,请各位大佬指点一下~~~~~
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication2 { public delegate void mydelegate();//声明一个无参数、返回值的委托 public delegate int mydelegate2();//声明一个返回值为int,无参数的的委托 public delegate int mydelegate3(int x, int y);//声明一个参数为int,返回值为int的委托 class Program { static void Main(string[] args) { mydelegate del = new mydelegate(M1);//在委托中实名注册了个M1命名方法 del(); mydelegate del4 = delegate() { Console.WriteLine("ok"); };//创建一个委托实例,里面包含一个匿名方法 del4(); mydelegate2 del2 = new mydelegate2(M2); var a = del2(); Console.WriteLine(a); mydelegate3 del3 = new mydelegate3(M3); var b = del3(4, 5); Console.WriteLine(b); Action act = new Action(M1);//系统内置委托Action方法,无返回值,无参数 act(); Action<int> act2 = new Action<int>(M4);//系统内置委托Action<>泛型方法,16个参数并且没有返回值 act2(44); Func<int, int, int> fun =new Func<int,int,int>(M3);//系统内置委托Func<>,16个参数,并且返回Tresult参数指定类型的值 Console.WriteLine(fun(3,4)); Func<int, int, int> funn = delegate(int x, int y) { return x + y; }; Console.WriteLine(funn(3, 4)); Func<int> fun2 = new Func<int>(M2); Console.WriteLine(fun2()); //lambda表达式的由来 mydelegate3 mylambda = delegate(int x, int y){ return x+y;};//匿名方法 mydelegate3 mylambda1 =(int x,int y)=>{return x+y;}; //lambda第一步简化,把匿名方法表达式中的delegate关键字去掉在参数和方法体之间加入=>lambda运算符读作gose to mydelegate3 mylambda2 = (x,y)=>{return x+y;};//编译器可以从委托的声明中知道委托的类型,从而可以在简化 ,省去参数类型(即使用 隐式类型) mydelegate3 mylambda3 = (x,y)=>x+y;//如果lambda表达式只有一个参数,可以省略圆括号,lambda表达式的方法主题可以是语句块或表达式,如果是一个包含一条return表达式的语句块,可以将语句块替换为return关键字后面的表达式。 Func<int, int, int> fun3 = new Func<int, int, int>((int x, int y) => { return x + y; }); int d = fun3(4, 5); Func<int, int, int> func4 = new Func<int, int, int>((x, y) => { return x + y; }); int n = fun3(4, 5); Func<int, int, int> func5 = (x, y) => { return x + y; }; Func<int, int, int> func9 = (x, y) => x + y; Console.WriteLine( func9(98,45)); dosometing((x, y) => { return x + y; }, 4, 4);//当参数是委托时,我们可以传委托、匿名方法、lambda表达式 dosometing(delegate(int x ,int y){return x+y;},4,4); dosometing(M3,4,4); Console.ReadKey(); } static void M1() { Console.WriteLine("ok"); } static void M4(int x) { Console.WriteLine(x); } static int M2() { return 3; } static int M3(int x, int y) { return x + y; } static void dosometing<T>(Func<T,T,T> fn ,T x ,T y) {//委托当做参数使用 T res= fn(x,y); Console.WriteLine(res); } } }