为什么在C#中if和委托的范围如此 [英] Why is the scope of if and delegates this way in c#

查看:59
本文介绍了为什么在C#中if和委托的范围如此的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

受此问题的启发,我开始想知道为什么以下所有示例都是在C#中是非法的:

Inspired by this question I began wondering why the following examples are all illegal in c#:

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

int i = 1;

{
   int i = 0;
}

int i = 1;

我只是想知道是否有人知道这种语言设计的确切原因?是否要阻止不良的编程习惯?如果是,为什么不只是发出警告?是出于性能原因(编译时以及运行时)还是出于什么原因?

I'm just wondering if anyone knew the exact reason why the language was designed this way? Is it to discourage bad programming practice, and if so why not just issue a warning?, for performance reasons (compiling and when running) or what is the reason?

推荐答案

C#语言规范的第3节介绍了此行为.这是规范的报价

This behavior is covered in section 3 of the C# language specification. Here is the quote from the spec

类似地,任何表达 发生为匿名者的身体 功能形式 lambda-expression创建一个 声明空间,其中包含 匿名函数的参数. 两个成员的错误 局部变量声明空间 具有相同的名称.这是一个错误 局部变量声明空间 一个块和一个嵌套的局部变量 包含元素的声明空间 同名.因此,在 嵌套的声明空间不是 可以声明局部变量 或与a相同名称的常量 局部变量或常量 封闭声明空间.

Similarly, any expression that occurs as the body of an anonymous function in the form of a lambda-expression creates a declaration space which contains the parameters of the anonymous function. It is an error for two members of a local variable declaration space to have the same name. It is an error for the local variable declaration space of a block and a nested local variable declaration space to contain elements with the same name. Thus, within a nested declaration space it is not possible to declare a local variable or constant with the same name as a local variable or constant in an enclosing declaration space.

我认为更容易理解的是,出于变量声明(以及许多其他与块相关的功能)的目的,将lambda/匿名委托块与普通块区别对待.

I think the easier way to read this is that for the purpose of variable declaration (and many other block related functions) a lambda/anonymous delegate block are treated no different than a normal block.

关于为什么以这种方式设计语言的原因,规范未明确说明.我的看法虽然简单.如果将代码视为仅另一个块,那么它会使代码分析例程更容易.您可以保留所有现有例程,以分析块中的语义错误和名称解析.当您考虑变量提升时,这一点尤其重要. Lambda最终将是一个不同的函数,但它们仍可以在声明点访问所有范围变量.

As to why the the language was designed this way the spec does not explicitly state. My opinion though is simplicity. If the code is treated as just another block then it makes code analysis routines easier. You can preserve all of your existing routines to analyze the block for semantical errors and name resolution. This is particularly important when you consider variable lifting. Lambdas will eventually be a different function but they still have access to all in scope variables at the declaration point.

这篇关于为什么在C#中if和委托的范围如此的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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