您的位置:首页 > 其它

防止Lambda的各种坑爹(一)

2012-12-02 14:25 183 查看
  1.奇怪的被捕获的变量:

View Code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TestLambda
{
class Program
{
static void Main(string[] args)
{
Action action = CreateAction();
action();
action();
action();

var a = DynamicCreateAction();
a();
a();
a();

Console.Read();
}

static Action CreateAction()
{
int value = 0;
Action action = () => Console.Write(value++);
return action;
}

static Action DynamicCreateAction()
{
DisplayClass d = new DisplayClass();

Action action = new Action(d.Print);
return action;
}

class DisplayClass
{
public int Value { get; set; }

public void Print()
{
Console.Write(Value++);
}
}

}

}


  OK,我想你现在明白了,"局部变量“不一定是局部的了吧。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: