在 C# 中,变量作用域(Scope) 是指变量在程序中可被访问的范围。变量只能在其定义的作用域内使用,超出作用域后将无法访问。
1. 局部变量作用域
局部变量声明在方法、代码块、循环或条件语句中,只能在当前代码块内访问。
cs
class Program
{
static void Main()
{
int a = 10;
if (a > 5)
{
int b = 20;
Console.WriteLine(b); // 正确
}
// Console.WriteLine(b); // 编译错误
}
}
2. 方法参数作用域
方法参数属于方法内部的局部变量,只能在当前方法内使用。
cs
static void Print(int num)
{
Console.WriteLine(num);
}
static void Main()
{
Print(100);
// Console.WriteLine(num); // 编译错误
}
3. 代码块作用域
由 {} 包围的区域形成独立作用域。
cs
{
int x = 100;
Console.WriteLine(x);
}
// Console.WriteLine(x); // 编译错误
4. for 循环变量作用域
循环变量仅在循环体内有效。
cs
for (int i = 0; i < 5; i++)
{
Console.WriteLine(i);
}
// Console.WriteLine(i); // 编译错误
5. 类成员变量作用域(字段)
字段属于类,可以被类中的所有方法访问。
cs
class Student
{
private string name = "Tom";
public void Show()
{
Console.WriteLine(name);
}
}
访问修饰符影响范围
| 修饰符 | 作用域 |
|---|---|
| private | 当前类 |
| protected | 当前类及子类 |
| internal | 当前程序集 |
| public | 所有地方 |
cs
public class User
{
private int age;
protected string name;
internal string address;
public string phone;
}
6. 静态变量作用域
静态变量属于类本身,而不是对象实例。
cs
class Counter
{
public static int Count = 0;
}
Counter.Count++;
Console.WriteLine(Counter.Count);
7. Lambda 表达式闭包作用域
Lambda 可以访问外部变量。
cs
int num = 10;
Action action = () =>
{
Console.WriteLine(num);
};
action();
修改外部变量
cs
int count = 0;
Action add = () =>
{
count++;
};
add();
Console.WriteLine(count); // 1
8. switch 作用域
不同 case 共用同一个作用域。
❌ 错误示例:
cs
switch (value)
{
case 1:
int num = 10;
break;
case 2:
int num = 20; // 编译错误
break;
}
✅ 正确写法:
cs
switch (value)
{
case 1:
{
int num = 10;
break;
}
case 2:
{
int num = 20;
break;
}
}
9. 变量隐藏(Shadowing)
内部作用域变量不能与外部同名。
cs
int age = 20;
{
// int age = 30; // 编译错误
}
类字段可被局部变量隐藏:
cs
class User
{
private string name = "Tom";
public void Show()
{
string name = "Jack";
Console.WriteLine(name); // Jack
Console.WriteLine(this.name); // Tom
}
}
10. 生命周期与作用域区别
作用域(Scope)
决定变量在哪里可以访问。
生命周期(Lifetime)
决定变量在内存中存在多久。
cs
void Test()
{
int x = 10;
}
- 作用域:
Test()方法内部 - 生命周期:方法执行期间
静态变量:
cs
class Test
{
public static int Count = 0;
}
- 作用域:类可访问范围
- 生命周期:程序启动到结束
示例总结
cs
class Program
{
static int globalVar = 100; // 类字段
static void Main()
{
int localVar = 10; // 局部变量
for (int i = 0; i < 3; i++)
{
int loopVar = i;
Console.WriteLine(
$"global={globalVar}, local={localVar}, loop={loopVar}");
}
// Console.WriteLine(loopVar); // 错误
}
}
作用域层级关系:
类作用域
└── 方法作用域
└── if作用域
└── for作用域
└── Lambda作用域
遵循原则:内层作用域可以访问外层变量,外层作用域不能访问内层变量。