71 lines
1.1 KiB
Markdown
71 lines
1.1 KiB
Markdown
# 静态类
|
||
概念:
|
||
用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. 只会==自动调用一次==
|