Files
My-Notes/笔记/CSharp/核心/静态类和静态构造函数.md
T
2026-06-18 20:01:30 +08:00

71 lines
1.1 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修饰
==只能包含静态成员==
==不能被实例化==
通常用法:
作为==工具类==方便使用
语法:
访问修饰符 static 类名(){}
案例:
```Csharp
public static class fun()
{
}
```
注意:
静态类不能被实例化,所以不能new
# 静态构造函数
概念:
staitc修饰
通常用法:
在静态函数中初始化静态变量
语法:
案例:
```Csharp
static class StaticClass
{
public static int testInt = 100;
public static int testInt2 = 100;
static StaticClass()
{
Console.WriteLine("静态构造函数");
}
}
```
↑运行后,在第一次使用该类会直接打印
```Csharp
class Test
{
public static int testInt = 200;
static Test()
{
Console.WriteLine("静态构造函数");
}
public Test()
{
Console.WriteLine("普通构造函数");
}
}
```
↑运行后,在第一次使用该类会在所有操作前先调用静态构造函数
注意:
1. 静态类和普通类都可以用
2. 不能使用访问修饰符
3. ==不能有参数==
4. 只会==自动调用一次==