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

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

问题描述

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天全站免登陆