Files
My-Notes/笔记/CSharp/核心/静态成员.md
T
2026-06-21 09:51:55 +08:00

69 lines
1.6 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# 静态成员
概念:
-`static` 修饰的成员叫静态成员
- 静态成员属于==类型本身==,不属于某个具体对象
- 常见的静态成员有:静态字段、静态方法、静态属性、静态事件
特点:
- 一般通过==类名.成员名==访问
- 同一类型的所有对象共享同一份静态数据
通常用法:
- 记录全局共享状态
- 写工具方法
- 定义不会因对象不同而变化的数据
案例:
```csharp
class Player
{
public static int Count;
public string Name;
public Player(string name)
{
Name = name;
Count++;
}
public static void PrintCount()
{
Console.WriteLine(Count);
}
}
Player p1 = new Player("A");
Player p2 = new Player("B");
Player.PrintCount(); // 2
```
注意:
1. ==静态成员属于类,不属于对象==
2. 静态方法里不能直接访问实例成员,因为它没有 `this`
3. 实例方法里可以访问静态成员
4. 静态字段通常会随着类型存在而存在;在大多数日常程序里,可以近似理解为“程序结束前一直都在”
5. 静态成员不是“永远不释放”的绝对规则,别把它和 GC 机制混为一谈
[[常量|const]] 和 `static readonly`
共同点:
- 都常用来表示“不希望随便改”的值
区别:
1. `const`
- 必须声明时初始化
- 编译期常量
- 隐式就是静态语义
2. `static readonly`
- 可以声明时赋值,也可以在静态构造函数中赋值
- 运行期确定
- 更适合保存复杂初始化结果
例子:
```csharp
class MathInfo
{
public const float Pi = 3.1415926f;
public static readonly DateTime StartTime = DateTime.Now;
}
```