我想如果在不同的范围内我可以声明两个变量具有相同的名称:
namespace IfScope
{
class Demo
{
public static void Main()
{
bool a = true;
if (a)
{
int i = 1;
}
string i = "s";
}
}
}
编译器说别的:
$ csc Var.cs
Microsoft (R) Visual C# 2010 Compiler version 4.0.30319.1
Copyright (C) Microsoft Corporation. All rights reserved.
Var.cs(13,20): error CS0136: 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
声明里面,如果外面是可见的(这是我的理解)
但是,如果我尝试使用它,然后我得到这个。
$ cat Var.cs
namespace IfScope
{
class Demo
{
public static void Main()
{
bool a = true;
if (a)
{
int i = 1;
}
i = "s";
}
}
}
Var.cs(13,14): error CS0103: The name 'i' does not exist in the current context
很明显,但是这里发生了什么?
[1]:http://stackoverflow.com/questions/2049330/c-sharp-variable-scoping – Sandeep 2012-04-02 22:33:05
是的,绝对重复 – 2012-04-02 22:34:16
简短回答:一个局部变量在声明它的整个块的范围内。也就是说,它的范围包括声明前块的部分。请参阅规格的第3.7节(v 4.0)。范围因此不是分开的。 – phoog 2012-04-03 18:14:22