迭代器变量超出C#的范围

时间:2013-04-30 19:02:13

标签: c# compiler-errors

为什么我在C#中写这个:

for(int myVar = 0; myVar<10; myVar++)
{
//do something here
}

//then, if I try:
int myVar = 8;
//I get some error that the variable is already declared.

//but if I try:
Console.WriteLine(myVar);
//then I get the error that the variable is not declared.

我最常说的有点困惑。有谁知道为什么C#编译器会这样做?

4 个答案:

答案 0 :(得分:6)

此规则以及其他一些相关规则在this blog post of Eric Lippert's中进行了讨论。

此处违反的特定规则是:

  

2)在同一局部变量声明空间或嵌套局部变量声明空间中有两个同名的局部变量是非法的。

特别值得注意的是,关于规则存在的原因如下:

  

所有这些规则的目的是防止代码的读者/维护者被欺骗的类错误,他们认为他们指的是一个名称简单的实体,但事实上是偶然引用另一个实体完全。这些规则特别旨在防止在执行应该是安全的重构时出现令人讨厌的意外。

通过允许你所描述的内容,它可能会导致看似良性的重构,例如将for循环移到另一个声明之后,导致行为大不相同。

答案 1 :(得分:1)

  

无法在此范围内声明名为“myVar”的局部变量,因为它会为“myVar”赋予不同的含义,“myVar”已在“子”范围内用于表示其他内容。

两个变量都在同一范围内声明。 (一个在子范围内仍然不会让你声明它两次)你不能再次声明变量。
更改scope将允许您再次声明它。

private void myMethod()
{
   //Start of method scope 

   for (int myVar = 0; myVar < 10; myVar ++)
   {
      //Start of child scope
      //End of child scope
   }

   //End of method scope
}

private void anotherMethod()
{
   // A different scope 
   int myVar = 0 
}

答案 2 :(得分:0)

您所指的already declared错误非常具有描述性,并且说...

  

无法在此范围内声明名为“myVar”的局部变量   因为它会给'myVar'赋予不同的含义,这已经是   用于“子”范围以表示其他内容

当你第二次尝试使用它时,

myVar实际上并没有'声明'。

答案 3 :(得分:0)

看起来很奇怪,但C#提供了一些代码行,只需使用这样的大括号:

for(int myVar = 0; myVar<10; myVar++)
{
//do something here
}

{
   //then, if I try:
   int myVar = 8;
   //I get some error that the variable is already declared.

   //but if I try:
   Console.WriteLine(myVar);
   //then I get the error that the variable is not declared.
}