静态类和静态构造函数
静态类
用static修饰的类
只能包含静态成员且不能被实例化
static class TestStatic
{
//静态成员变量
public static int testIndex = 0;
//静态方法
public static void TestFun()
{
}
//静态成员属性
public static int TestIndex
{
get;
set;
}
}
静态构造函数
在构造函数前加上 static 修饰
不能有参数,不能使用访问修饰符,只会自动调用一次
static class StaticClass
{
public static int testInt = 100;
public static int testInt2=100;
//静态构造函数
static StaticClass()
{
Console.WriteLine("静态构造函数");
}
}
静态构造函数会在第一次使用类中的内容时会调用一次
普通类中的静态构造函数
class Test
{
public static int testInt =200;
static Test()
{
Console.WriteLine("静态构造");
}
//普通构造函数和静态构造函数不属于同类,不会触发重载
public Test()
{
Console.WriteLine("普通构造函数");
}
}

浙公网安备 33010602011771号