C# 变量作用域的实现示例
作者:逝水无殇
本文介绍了C#中的变量作用域规则,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
在 C# 中,变量作用域(Scope) 是指变量在程序中可被访问的范围。变量只能在其定义的作用域内使用,超出作用域后将无法访问。
1. 局部变量作用域
局部变量声明在方法、代码块、循环或条件语句中,只能在当前代码块内访问。
class Program
{
static void Main()
{
int a = 10;
if (a > 5)
{
int b = 20;
Console.WriteLine(b); // 正确
}
// Console.WriteLine(b); // 编译错误
}
}2. 方法参数作用域
方法参数属于方法内部的局部变量,只能在当前方法内使用。
static void Print(int num)
{
Console.WriteLine(num);
}
static void Main()
{
Print(100);
// Console.WriteLine(num); // 编译错误
}3. 代码块作用域
由 {} 包围的区域形成独立作用域。
{
int x = 100;
Console.WriteLine(x);
}
// Console.WriteLine(x); // 编译错误4. for 循环变量作用域
循环变量仅在循环体内有效。
for (int i = 0; i < 5; i++)
{
Console.WriteLine(i);
}
// Console.WriteLine(i); // 编译错误5. 类成员变量作用域(字段)
字段属于类,可以被类中的所有方法访问。
class Student
{
private string name = "Tom";
public void Show()
{
Console.WriteLine(name);
}
}访问修饰符影响范围
| 修饰符 | 作用域 |
|---|---|
| private | 当前类 |
| protected | 当前类及子类 |
| internal | 当前程序集 |
| public | 所有地方 |
public class User
{
private int age;
protected string name;
internal string address;
public string phone;
}6. 静态变量作用域
静态变量属于类本身,而不是对象实例。
class Counter
{
public static int Count = 0;
}
Counter.Count++;
Console.WriteLine(Counter.Count);7. Lambda 表达式闭包作用域
Lambda 可以访问外部变量。
int num = 10;
Action action = () =>
{
Console.WriteLine(num);
};
action();修改外部变量
int count = 0;
Action add = () =>
{
count++;
};
add();
Console.WriteLine(count); // 18. switch 作用域
不同 case 共用同一个作用域。
❌ 错误示例:
switch (value)
{
case 1:
int num = 10;
break;
case 2:
int num = 20; // 编译错误
break;
}✅ 正确写法:
switch (value)
{
case 1:
{
int num = 10;
break;
}
case 2:
{
int num = 20;
break;
}
}9. 变量隐藏(Shadowing)
内部作用域变量不能与外部同名。
int age = 20;
{
// int age = 30; // 编译错误
}类字段可被局部变量隐藏:
class User
{
private string name = "Tom";
public void Show()
{
string name = "Jack";
Console.WriteLine(name); // Jack
Console.WriteLine(this.name); // Tom
}
}10. 生命周期与作用域区别
作用域(Scope)
决定变量在哪里可以访问。
生命周期(Lifetime)
决定变量在内存中存在多久。
void Test()
{
int x = 10;
}- 作用域:
Test()方法内部 - 生命周期:方法执行期间
静态变量:
class Test
{
public static int Count = 0;
}- 作用域:类可访问范围
- 生命周期:程序启动到结束
示例总结
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作用域遵循原则:内层作用域可以访问外层变量,外层作用域不能访问内层变量。
到此这篇关于C# 变量作用域的实现示例的文章就介绍到这了,更多相关C# 变量作用域内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
