今天代碼Review發現的C#閉包問題,請做題

來源:互聯網
上載者:User

今天給同事的代碼做了一個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對很多語言也是一樣。徹底搞搞明白對你沒壞處,你說對不?本文相關的基礎知識網上、書上都有,這裡就不重複了。(:本文不適合高手和高高手閱讀,我也不想浪費您寶貴的時間,請繞行~)

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.