问题描述
我发现以下内容很奇怪.再说一次,我主要在动态语言中使用闭包,这不应该被同一个错误"怀疑.以下使编译器不高兴:
I found the following rather strange. Then again, I have mostly used closures in dynamic languages which shouldn't be suspectable to the same "bug". The following makes the compiler unhappy:
VoidFunction t = delegate { int i = 0; };
int i = 1;
上面写着:
名为i"的局部变量不能在此范围内声明,因为它会给'i'赋予不同的含义,已在孩子"中使用表示其他东西的范围
A local variable named 'i' cannot be declared in this scope because it would give a different meaning to 'i', which is already used in a 'child' scope to denote something else
所以这基本上意味着在委托中声明的变量将具有在其中声明的函数的范围.这并不完全是我所期望的.我什至没有尝试调用该函数.至少 Common Lisp 有一个特性,你说一个变量应该有一个动态名称,如果你真的希望它是本地的.这在创建不泄漏的宏时尤其重要,但类似的东西在这里也很有帮助.
So this basically means that variables declared inside a delegate will have the scope of the function declared in. Not exactly what I would have expected. I havn't even tried to call the function. At least Common Lisp has a feature where you say that a variable should have a dynamic name, if you really want it to be local. This is particularly important when creating macros that do not leak, but something like that would be helpful here as well.
所以我想知道其他人如何解决这个问题?
So I'm wondering what other people do to work around this issue?
为了澄清,我正在寻找一种解决方案,其中我在委托中声明的变量不会干扰在委托之后声明的变量.而且我希望仍然能够捕获在委托之前声明的变量.
To clarify I'm looking for a solution where the variables I declare in the delegete doesn't interfere with variables declared after the delegate. And I want to still be able to capture variables declared before the delegate.
推荐答案
必须是这样才能允许匿名方法(和 lambdas)使用包含方法中的局部变量和参数.
It has to be that way to allow anonymous methods (and lambdas) to use local variables and parameters scoped in the containing method.
解决方法是为变量使用不同的名称,或者创建一个普通的方法.
The workarounds are to either use different names for the variable, or create an ordinary method.
这篇关于委托中的变量范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!