代理范围变量 [英] Scope of variables in a delegate

查看:141
本文介绍了代理范围变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现以下很奇怪。那么再次,我主要以动态语言使用闭包,不应该怀疑相同的bug。以下使编译器不开心:

  VoidFunction t = delegate {int i = 0; }; 

int i = 1;

它说:


一个名为'i'的局部变量不能在此范围内声明为
,因为
会给i一个不同的含义,
已经在child
范围来表示别的东西


所以这基本上意味着在委托中声明的变量将声明的函数的范围不完全是我预期的。我甚至没有试图调用这个功能。至少Common Lisp有一个功能,你说如果你真的希望它是本地变量应该有一个动态名称。这在创建没有泄漏的宏时尤其重要,但是这样的东西在这里也是有帮助的。



所以我想知道其他人在做什么这个问题?



为了澄清我正在寻找一个解决方案,其中我在debgete中声明的变量不会影响 后声明的变量代表。而且我想仍然能够捕获在委托之前声明的变量。

解决方案

它必须是允许匿名方法(和lambdas)使用在包含方法中限定的局部变量和参数。



解决方法是为变量使用不同的名称,或创建一个普通的方法。 / p>

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;

It says:

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

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.

解决方案

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.

这篇关于代理范围变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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