{}),你的变量就失效了。
定义在方法(函数)内部的变量。它的有效期仅限于这个方法的大括号 {} 之内。
class Program
{
static void Main(string[] args)
{
int money = 100; // 局部变量,只在 Main 里有效
if (true)
{
int secret = 50; // 更局部的变量,只在这个 if 块里有效
Console.WriteLine(money); // 可以访问外面的
}
// Console.WriteLine(secret); // 错误!出了 if 块,secret 已经烟消云散了!
}
static void OtherMethod()
{
// Console.WriteLine(money); // 错误!Main 里的钱,这里拿不到!
}
}
定义在类(Class)里面,但在方法外面的变量。整个类里的所有方法都可以访问它。
class HuaShan
{
static string sectRule = "君子剑"; // 成员变量(如果是 static,则是全门派共享)
static void Method1()
{
Console.WriteLine(sectRule); // 可以访问
}
static void Method2()
{
Console.WriteLine(sectRule); // 也可以访问
}
}
观察下面的代码,哪一行会报错?
void Test()
{
int a = 10;
{
int b = 20;
Console.WriteLine(a); // line 1
}
Console.WriteLine(b); // line 2
}
line 2 会报错!
因为 b 是在内部的大括号里定义的,出了那个括号,它就“死”了。岳不群会告诉你:The name 'b' does not exist in the current context.