c#静态类和静态构造函数

静态类

用static修饰类

只能包含静态成员

不能被实例化

将常用的静态 成员写在静态类中 方便使用

静态类不能被实例化,更能体现工具类的唯一性

适合做工具类

cs 复制代码
static class TestStatic
{
    
    public static int value=0;
    public static void TestFun()
    {

    }
    public static int TestIndex
    {
        get
        {
            return TestIndex;
        }
        set
        {

        }
    }

}

静态构造函数

在构造函数上加static修饰

静态类和普通类都可以有

不能使用访问修饰符

不能有参数

只会自动调用一次

使用

在静态构造函数中初始化 静态变量

静态类中的静态构造函数

cs 复制代码
static class StaticClass
{
    public static int testInt = 100;
    public static int testInt2 = 200;
    static StaticClass()
    {
        Console.WriteLine("**");
        Console.WriteLine(StaticClass.testInt);
        Console.WriteLine(testInt);
    }
}

普通类中的静态构造函数

cs 复制代码
 class Test
 {
     public static int testInt = 200;
     static Test()
     {
         Console.WriteLine("静态构造");
     }
     public  Test()
     {
         Console.WriteLine("普通构造");
     }
 }

Console.WriteLine(StaticClass.testInt);//在第一次使用时 就会调用

Test t = new Test();//两个对象 但是只调用了一次 。在你第一次使用这个类时就会自动调用

Test t2 = new Test();

cs 复制代码
Console.WriteLine(StaticClass.testInt);
Test t = new Test();
Test t2 = new Test();
相关推荐
雨落倾城夏未凉2 天前
第四章c#方法-参数数组和可选参数(16)
后端·c#
唐青枫3 天前
线程不是越多越快:C#.NET Thread 生命周期、同步与后台工作线程实战
c#·.net
唐青枫4 天前
别只会反射:C#.NET Emit 动态生成代码实战详解
c#·.net
咕白m6254 天前
.NET 环境下 Word 超链接批量提取方案
c#·.net
用户91721561902114 天前
C# 通信协议增量解析:用状态机处理半包和粘包
c#
小码编匠5 天前
C# 工控上位机必备:数据转换工具类与十个核心模块
后端·c#·.net
唐青枫7 天前
别再乱用 StartNew:C#.NET TaskFactory 任务调度实战详解
c#·.net
Artech7 天前
[MAF预定义的AIContextProvider-03]ChatHistoryMemoryProvider——赋予Agent从经验中学习的能力
ai·c#·agent·memory·maf
Scout-leaf9 天前
C#摸鱼实录——IoC与DI案例详解
c#
咕白m6259 天前
使用 C# 在 Excel 中应用多种字体样式
后端·c#