Scope of variables in a delegate(委托中的变量范围)
问题描述
我发现以下内容很奇怪.再说一次,我主要在动态语言中使用闭包,这不应该被同一个错误"怀疑.以下使编译器不高兴:
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.
这篇关于委托中的变量范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:委托中的变量范围
基础教程推荐
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- 如何激活MC67中的红灯 2022-01-01
- rabbitmq 的 REST API 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- c# Math.Sqrt 实现 2022-01-01
- 将 XML 转换为通用列表 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01