闭包对象:如果匿名方法引用了某个局部变量,编译器就会自动将该引用提升到该闭包对象当中。
class Program { static void Main(string[] args) { List<Action> listAction = new List<Action>(); for (int i = 0; i < 5; i++) { Action t = () => { Console.WriteLine(i); }; listAction.Add(t); } Console.WriteLine(); foreach (var a in listAction) { a(); } Console.WriteLine(); Console.WriteLine("----test02----"); TempClass tempClass = new TempClass(); // 闭包对象 List<Action> list01 = new List<Action>(); for (tempClass.i = 0; tempClass.i < 5; tempClass.i++) { Action a01 = () => { tempClass.TempFuc(); }; list01.Add(a01); } foreach (Action a in list01) { a(); } Console.WriteLine(); Console.WriteLine("---去闭包对象---"); List<Action> list02 = new List<Action>(); for (int i = 0; i < 5; i++) { TempClass tempClass01 = new TempClass(); Console.WriteLine(tempClass01.GetHashCode()); tempClass01.i = i; Action a01 = () => { tempClass01.TempFuc(); }; list02.Add(a01); } foreach (Action a in list02) { a(); } } } class TempClass { public int i; public void TempFuc() { Console.WriteLine(i.ToString()); } }
标签:闭包,Console,陷阱,List,WriteLine,Action,tempClass From: https://www.cnblogs.com/wen-chen/p/16994001.html