访问修改关闭 [英] Access to Modified Closure

查看:138
本文介绍了访问修改关闭的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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的抱怨,这是进入修改关闭,以做工精细。任何一个可以揭示出这个光?

The above seems to work fine though ReSharper complains that this is "access to modified closure". Can any one shed light on this?

(这个话题继续这里

推荐答案

在这种情况下,这没关系,因为你实际上是在执行委托的 的循环。

In this case, it's okay, since you are actually executing the delegate within the loop.

如果你保存的委托,然后再使用它,但是,你会发现,所有的代表会抛出异常尝试访问文件[I]时 - 他们捕捉的变量 I ,而不是其在委托创作的时间价值。

If you were saving the delegate and using it later, however, you'd find that all of the delegates would throw exceptions when trying to access files[i] - they're capturing the variable i rather than its value at the time of the delegates creation.

在总之,这是一个需要注意的一个的潜力的陷阱,但在这种情况下,它不会伤害你。

In short, it's something to be aware of as a potential trap, but in this case it doesn't hurt you.

请参阅本页面的底部更复杂的例子,结果是违反直觉的。

See the bottom of this page for a more complex example where the results are counterintuitive.

这篇关于访问修改关闭的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆