string [] files = new string[2];
files[0] = "ThinkFarAhead.Example.Settings.Configuration_Local.xml";
files[1] = "ThinkFarAhead.Example.Settings.Configuration_Global.xml";
//Resharper complains this is an "access to modified closure"
for (int i = 0; i < files.Length; i++ )
{
// Resharper disable AccessToModifiedClosure
if(Array.Exists(Assembly.GetExecutingAssembly().GetManifestResourceNames(),
delegate(string name) { return name.Equals(files[i]); }))
return Assembly.GetExecutingAssembly().GetManifestResourceStream(files[i]);
// ReSharper restore AccessToModifiedClosure
}
上面的工作似乎很好,尽管ReSharper抱怨这是“访问修改闭包”。有人能解释一下吗?
(这个话题在这里继续)
我知道这是一个老问题,但我最近一直在研究闭包,并认为一个代码示例可能会有用。在幕后,编译器生成一个表示函数调用的词法闭包的类。它可能看起来像这样:
private sealed class Closure
{
public string[] files;
public int i;
public bool YourAnonymousMethod(string name)
{
return name.Equals(this.files[this.i]);
}
}
如上所述,您的函数可以工作,因为谓词在创建后立即被调用。编译器将生成如下内容:
private string Works()
{
var closure = new Closure();
closure.files = new string[3];
closure.files[0] = "notfoo";
closure.files[1] = "bar";
closure.files[2] = "notbaz";
var arrayToSearch = new string[] { "foo", "bar", "baz" };
//this works, because the predicates are being executed during the loop
for (closure.i = 0; closure.i < closure.files.Length; closure.i++)
{
if (Array.Exists(arrayToSearch, closure.YourAnonymousMethod))
return closure.files[closure.i];
}
return null;
}
另一方面,如果要存储谓词,然后再调用谓词,则会看到对谓词的每次调用实际上都是在闭包类的同一个实例上调用相同的方法,因此i将使用相同的值。
"files"是一个被捕获的外部变量,因为它已被匿名委托函数捕获。匿名委托函数延长了它的生命周期。
捕获外部变量
当外部变量被匿名函数引用时,外部变量被匿名函数捕获。通常,局部变量的生命周期仅限于与之相关的块或语句的执行(局部变量)。但是,捕获的外部变量的生命周期至少会延长到从匿名函数创建的委托或表达式树适合垃圾收集为止。
MSDN的外部变量
When a local variable or a value parameter is captured by an anonymous function, the local variable or parameter is no longer considered to be a fixed variable (Fixed and moveable variables), but is instead considered to be a moveable variable. Thus any unsafe code that takes the address of a captured outer variable must first use the fixed statement to fix the variable.
Note that unlike an uncaptured variable, a captured local variable can be simultaneously exposed to multiple threads of execution.