C#基础知识---匿名方法使用
一、匿名方法使用
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 7 namespace AnonymousMethod 8 { 9 delegate void DelegateWithoutArguments(); 10 delegate void DelegateWithArguments(string str); 11 class Program 12 { 13 static void Main(string[] args) 14 { 15 DelegateWithoutArguments del1 = delegate 16 { 17 Console.WriteLine("I am a delegate without arguments"); 18 };//使用匿名函数初始化委托 19 DelegateWithoutArguments del2 = new DelegateWithoutArguments(Test1);//使用静态函数初始化委托 20 del1(); 21 del2(); 22 23 DelegateWithArguments del3 = delegate (string str) 24 { 25 Console.WriteLine(str); 26 }; 27 DelegateWithArguments del4 = new DelegateWithArguments(Test2); 28 del3("I am a delegate with one argument"); 29 del4("I am a delegate with one argument"); 30 Console.Read(); 31 32 33 } 34 static void Test1() 35 { 36 Console.WriteLine("I am a delegate without arguments"); 37 } 38 static void Test2(string str) 39 { 40 Console.WriteLine(str); 41 } 42 } 43 }