理解 C# 变量作用域:类级、方法级与块级详解
理解 C# 变量作用域
本指南解释 C# 变量作用域机制,涵盖类级、方法级、块级三大作用域,配以清晰实战示例。
变量作用域决定变量在代码中的可访问范围。C# 中主要有三种作用域。
- 类级作用域
- 方法级作用域
- 块级作用域
类级变量作用域
在类内部但方法/构造函数外部声明的变量称为字段,可被该类所有成员访问,称为 类级作用域。
using System;
namespace VariableScope {
class Program {
// 类级字段
string str = "Class Level";
public void Display() {
Console.WriteLine(str);
}
static void Main(string[] args) {
Program ps = new Program();
ps.Display();
Console.ReadLine();
}
}
}
输出
Class Level
str 作为字段,在整个 Program 类中可用,包括 Display 方法。
重要提示: 实例字段不能从静态方法直接访问,除非通过实例。例如:
static void Display2() {
// 编译错误
Console.WriteLine(str);
}
方法级变量作用域
在方法内部声明的变量为局部变量,仅在该方法内可用,称为 方法级作用域。
using System;
namespace VariableScope {
class Program {
public void Method1() {
// 局部变量
string str = "method level";
}
public void Method2() {
// 此处访问 str 将报错
Console.WriteLine(str);
}
static void Main(string[] args) {
Program ps = new Program();
ps.Method2();
Console.ReadLine();
}
}
}
在 Method2 中使用 str 导致编译错误:
Error CS0103: The name 'str' does not exist in the current context
反之,局部变量可在同一方法内使用:
using System;
namespace VariableScope {
class Program {
public void Display() {
string str = "inside method";
Console.WriteLine(str);
}
static void Main(string[] args) {
Program ps = new Program();
ps.Display();
Console.ReadLine();
}
}
}
输出
inside method
块级变量作用域
在块(如循环、if 语句或其他嵌套作用域)内声明的变量仅在该块内可访问,称为 块级作用域。
using System;
namespace VariableScope {
class Program {
public void Display() {
for (int i = 0; i <= 3; i++) {
// i 仅限于此 for 循环块
}
// Console.WriteLine(i); // ❌ 编译错误
}
static void Main(string[] args) {
Program ps = new Program();
ps.Display();
Console.ReadLine();
}
}
}
循环计数器 i 在循环结束后不可引用,因其作用域随块结束而终止。
C语言