今天代码Review发现的C#闭包问题,请做题
今天给同事的代码做了一个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对很多语言也是一样。彻底搞搞明白对你没坏处,你说对不?本文相关的基础知识网上、书上都有,这里就不重复了。(注:本文不适合高手和高高手阅读,我也不想浪费您宝贵的时间,请绕行~)

