【发布时间】:2010-10-07 22:46:07
【问题描述】:
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 作为参数。
【问题讨论】:
标签: c# .net function closures anonymous-methods