今天給同事的代碼做了一個CodeReview,發現了一些潛在的問題/bug,有很多是基於C#的文法糖很炫而又不理解其深層含義導致。下面就舉個例子,是關於C#的閉包的,新手很容易犯,你看看下面的程式,能不能寫出程式的運行結果呢?
using System;namespace ConsoleApplication2{ class Program { static void Main(string[] args) { var t = new Test(); Console.WriteLine("Start 1: "); t.DoTask(""); Console.WriteLine("Start 2: "); t.DoTask("", 1); Console.WriteLine("Done."); Console.Read(); } } public class Test { private TaskExecutor _taskExecutor; private int _temp; public void DoTask(string args1, long? args2 = null) { if(_taskExecutor == null) _taskExecutor=new TaskExecutor(); _temp++; _taskExecutor.Completed += (s, e) => Console.WriteLine("Completed! _temp = {0}, Args2 = {1}", _temp.ToString(), args2.HasValue ? args2.ToString() : "null"); _taskExecutor.Start(); } } public delegate void OnCompletedEventHandler(object sender, EventArgs e); public class TaskExecutor { public void Start() { System.Threading.Thread.Sleep(1000);//Execute long task.... OnCompleted(); } public event OnCompletedEventHandler Completed; private void OnCompleted() { if (Completed != null) { Completed(this, new EventArgs()); } } }}
運行結果是:(先別看,做了再點擊)
都說沒文化真可怕,套到這裡叫做:基礎不牢真可怕。C#文法糖確實很甜,匿名函數、Lambda、閉包,的確很帥,但如果我們不理解它們,恐怕代碼bug產出率會很高;其實JS閉包,C#閉包,Java閉包都一個道理,搞明白了一通百通,Lambda對很多語言也是一樣。徹底搞搞明白對你沒壞處,你說對不?本文相關的基礎知識網上、書上都有,這裡就不重複了。(注:本文不適合高手和高高手閱讀,我也不想浪費您寶貴的時間,請繞行~)