奇怪的局部变量
奇怪的局部变量:讨论一下C#中的闭包
[0]静态全局字段
using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace ConsoleApplication3{ class Program { public static int copy;//[0]这个不是闭包 static void Main() { //定义动作组 List<Action> actions = new List<Action>(); for (int counter = 0; counter < 10; counter++) { copy = counter; actions.Add(() => Console.WriteLine(copy)); } //执行动作 foreach (Action action in actions) action(); } }}//注:Action定义如下://public delegate void Action();using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace ConsoleApplication3{ class Program { static void Main() { int copy;//[1]闭包一 //定义动作组 List<Action> actions = new List<Action>(); for (int counter = 0; counter < 10; counter++) { copy = counter; actions.Add(() => Console.WriteLine(copy)); } //执行动作 foreach (Action action in actions) action(); } }}//注:Action定义如下://public delegate void Action();using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace ConsoleApplication3{ class Program { static void Main() { //定义动作组 List<Action> actions = new List<Action>(); for (int counter = 0; counter < 10; counter++) { int copy;//[1]闭包二 copy = counter; //int copy = counter;//换种写法 actions.Add(() => Console.WriteLine(copy)); } //执行动作 foreach (Action action in actions) action(); } }}//注:Action定义如下://public delegate void Action();using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace ConsoleApplication3{ class Program { static void Main() { //定义动作组 List<Action> actions = new List<Action>(); for (int counter = 0; counter < 10; counter++)//[3]闭包三 { actions.Add(() => Console.WriteLine(counter)); } //执行动作 foreach (Action action in actions) action(); } }}//注:Action定义如下://public delegate void Action();
[解决办法]
看看生成的il代码就一清二楚为什么会有这样的结果了
[解决办法]
这几个例子,可以将匿名函数进行转换,这样可以看的更清楚
在[0]中,“外部变量”copy是类的一个静态成员,因此可以讲匿名函数转换为以下形式:
class Program { public static int copy;//[0]这个不是闭包 static void TempMethod() { Console.WriteLine(copy); } static void Main() { //定义动作组 List<Action> actions = new List<Action>(); for (int counter = 0; counter < 10; counter++) { copy = counter; actions.Add(new Action(TempMethod)); } //执行动作 foreach (Action action in actions) action(); } }
[解决办法]
for (int counter = 0; counter < 10; counter++)//[3]闭包三 { actions.Add(() => Console.WriteLine(counter)); }
[解决办法]
再举例一个解决方案:
static void Main(string[] args) { List<Action> actions = new List<Action>(); Action<int> assign = (i) => actions.Add(() => Console.WriteLine(i)); for (int counter = 0; counter < 10; counter++) { assign(counter); } foreach (Action action in actions) action(); }
[解决办法]