1. 程式人生 > 實用技巧 >[C#] 委託與匿名方法

[C#] 委託與匿名方法

using System; namespace 匿名函式 { class Program { delegate void TestDelegate(string s); static void M(string s) { Console.WriteLine("A引數為:{0}", s); } static void Main(string[] args) { //1. 委託的基本寫法,及呼叫 TestDelegate testDeleA = new TestDelegate(M);//通過委託的例項化將之與方法繫結 testDeleA("hahahah"); //2. 使用匿名錶達式構造委託呼叫方法
//C#2.0 Anonymous Method,其結構為:delegate+(各個引數)+{函式體} TestDelegate testDeleB = delegate (string s) { Console.WriteLine("B引數為:{0}", s); };//直接通過delegate宣告將之與函式體繫結 testDeleB("hehehehe"); //C#3.0, 引入lamda表達法,Lambda Expression TestDelegate testDeleC = (x) => { Console.WriteLine("C引數為:{0}", x); }; testDeleC("hohoho"
); Console.ReadKey(); } } }