我以为如果在不同的作用域中,我可以使用同一个名称声明两个变量:
编译器说了另外一件事:
显然,但这里发生了什么?
可能是重复问题:
C# 变量作用域
我认为如果在不同的作用域中,我可以使用相同的名称来声明两个变量:
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
这意味着在if语句中声明的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
显然,但这里发生了什么?