复制 lambda/ 匿名方法捕获的变量时的术语
我翻译了这段代码(它有不好的副作用,它只捕获外部变量):
foreach (TaskPluginInfo tpi in Values)
{
GenerateMenu(menuStrip, tpi.MenuTree, tpi.MenuText, delegate { tpi.ShowTask() });
}
对于这段代码(因为上面不起作用):
foreach (TaskPluginInfo tpi in Values)
{
// must capture the variable
var x = tpi;
GenerateMenu(menuStrip, tpi.MenuTree, tpi.MenuText, delegate { x.ShowTask(); });
}
针对那个鲜为人知的副作用的解决方法的正确术语是什么? 现在,我评论说“必须捕获变量”。 “捕获”这个词是正确的术语吗?
I translated this code(it has bad side effect that it just capture the outer variable):
foreach (TaskPluginInfo tpi in Values)
{
GenerateMenu(menuStrip, tpi.MenuTree, tpi.MenuText, delegate { tpi.ShowTask() });
}
To this code(because the above is not working):
foreach (TaskPluginInfo tpi in Values)
{
// must capture the variable
var x = tpi;
GenerateMenu(menuStrip, tpi.MenuTree, tpi.MenuText, delegate { x.ShowTask(); });
}
What's the correct terminology for that work-around on that little known side effect? For now, I commented "must capture the variable." Is the word capture, the correct terminology?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
好吧, tpi 和 x 都是在示例之一中捕获的变量(不同类型)...这里的要点是您想要限制捕获变量的范围(理想情况下< code>x) 到循环内部。
所以,也许; “捕获迭代变量的值;而不是迭代变量本身”
Well, both tpi and x are variables (of different sorts) that get captured in one of the examples... the main point here is that you want to restrict the scope of the captured variable (ideally
x
) to inside the loop.So, perhaps; "capture the value of the iteration variable; not the iteration variable itself"
您实际上要做的是创建一个闭包上下文,其中包含每次迭代的迭代器的值。 只要委托存在,该上下文就对委托保持可用。
您如何称呼您所指的声明? 我认为“捕获”是一个很好用的动词。 最后,只要大家都明白你的意思就可以了:-)
What you're actually doing is creating a closure context containing the value of the iterator for each iteration. This context will remain available to the delegate as long as the delegate exists.
How would you call the statement you're referring to? I think "capture" is a good verb to use. In the end, as long as it's clear to everyone what you mean, it's ok :-)
Resharper 的警告称这种情况为“访问修改后的闭包”,推荐的解决方案是“捕获变量”,因此在我的评论中我会说“必须捕获变量以避免访问修改后的闭包”。
Resharper's warning calls this scenario "Access to modified closure" and recommended solution is to "Capture variable" so in my comment I would say "Must capture variable to avoid access to modified closure".
关闭
closure
是的,这就是捕获; 您还可以使用“结束”。 这里有几个例句;
您可能还想搜索术语“自由变量”和“绑定变量”。
Yeah, it's capture; you can also use 'closes over'. Here are a couple of example sentences;
You might also want to google for the terms 'free variable' and 'bound variable'.
“将迭代变量分配给循环内的局部变量”
"assign the iteration variable to a local variable that's scoped inside the loop"