1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 7 namespace DelegatesAndLambda 8 { 9 //委托:定义了方法的类型,存储是一些具有相同签名(相同返回值、相同参数)的方法的地址列表 10 //泛型委托:委托重用 11 //lambda:本质来说是一个匿名方法 12 class Program 13 { 14 //自定义委托 15 delegate void hellodelegate(string msg); 16 17 //泛型委托 18 delegate void genericsDelegate<T>(T a); 19 20 static void Main(string[] args) 21 { 22 //初始化 23 hellodelegate hello = new hellodelegate(SayHelloByEglish); 24 genericsDelegate<string> gdl = new genericsDelegate<string>(SayHelloByEglish); 25 genericsDelegate<int> gdl2 = new genericsDelegate<int>(AddNum); 26 //预定义委托 27 //无返回值 28 Action<string> action = new Action<string>(SayHelloByEglish); 29 action("Speak English"); 30 //有返回值 TResult 返回值泛型 31 Func<string,string> func = new Func<string,string>(SayHelloToWorld); 32 Console.WriteLine(func("有返回值的预定义委托")); 33 34 //labmda表达式 35 //使用匿名方法 36 Action<string> action1 = new Action<string>(delegate (string msg) { 37 Console.WriteLine(msg); 38 }); 39 Action<string> action2 = new Action<string>((string msg) => { 40 Console.WriteLine(msg); 41 }); 42 //一个参数 一个语句 43 Action<string> action3 = new Action<string>( msg => { 44 Console.WriteLine(msg); 45 }); 46 //无参无返回值 47 Action action4 = new Action(() => { 48 Console.WriteLine(""); 49 }); 50 //调用 51 hello.Invoke("My Speck English"); 52 gdl("Say japanese"); 53 gdl2(5); 54 action1("匿名委托"); 55 Console.ReadKey(); 56 } 57 58 public static void SayHelloByEglish(string msg) 59 { 60 Console.WriteLine(msg); 61 } 62 63 public static void AddNum(int a) 64 { 65 Console.WriteLine(a + 5); 66 } 67 68 public static string SayHelloToWorld(string param) 69 { 70 return param; 71 } 72 } 73 74 }
原文:https://www.cnblogs.com/lvseamoon/p/14723044.html