testit() 方法是一个闭包。aString 已超出范围,但 testit() 仍然可以在其上执行。testit2() 使用的变量没有超出范围(mystring),但也没有传递给 testit2()。testit2() 是否被视为闭包?
string mystring = "hello world";
Action testit = new Action(delegate { string aString = "in anon method"; Debug.WriteLine(aString); });
testit();
//capture mystring. Is this still a closure?
Action testit2 = new Action(delegate { Debug.WriteLine(mystring); });
//mystring is still in scope
testit2();
在第二个示例中,可以在方法之外更新 mystring,这些更改将反映在 testit2() 中。这不像普通方法,它只能将 mystring 作为参数捕获。