为什么不能在一个嵌套的局部范围内重复的变量名声明? [英] Why can't a duplicate variable name be declared in a nested local scope?

查看:730
本文介绍了为什么不能在一个嵌套的局部范围内重复的变量名声明?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据最近这次<一个href="http://stackoverflow.com/questions/6155732/a-local-variable-cannot-be-declared-in-this-scopelinq-lambda-ex$p$pssion">question,我不明白,提供了答案。好像你应该​​能够做这样的事,因为他们的范围不重叠

 静态无效的主要()
{
  {
    INT I;
  }
  INT I;
}
 

这code编译失败,出现以下错误:

  

,命名为I不能在此范围内声明,因为以'我',将给予不同的意义的局部变量它已经用在'孩子'范围来表示别的东西

解决方案

我不认为任何的答案至今的非常的得到了规范的重要线路。

从第8.5.1节:

  

局部变量声明的是块声明的局部变量的范围,该声明所在。这是一个错误引用一个局部变量在于precedes局部变量的局部变量声明的文本位置。在局部变量的范围内,这是一个编译时错误声明另一个局部变量或常量具有相同的名称。

(重点煤矿。)

在换句话说,适用范围为后来的变量包含块的一部分的的声明 - 即它包含有早变量内块

您不能的引用的到后来的变量在一个地方早于它的声明 - 但它仍然在范围

Based on this recent question, I don't understand the answer provided. Seems like you should be able to do something like this, since their scopes do not overlap

static void Main()
{
  {
    int i;
  }
  int i;
}

This code fails to compile with the following error:

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

解决方案

I don't think any of the answers so far have quite got the crucial line from the spec.

From section 8.5.1:

The scope of a local variable declared in a local-variable-declaration is the block in which the declaration occurs. It is an error to refer to a local variable in a textual position that precedes the local-variable-declarator of the local variable. Within the scope of a local variable, it is a compile-time error to declare another local variable or constant with the same name.

(Emphasis mine.)

In other words, the scope for the "later" variable includes the part of the block before the declaration - i.e. it includes the "inner" block containing the "earlier" variable.

You can't refer to the later variable in a place earlier than its declaration - but it's still in scope.

这篇关于为什么不能在一个嵌套的局部范围内重复的变量名声明?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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