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();
相关推荐
星夜离尘5611 分钟前
MATLAB滑动RMS如何接报警:窗口未满和缺样不能当成正常
开发语言·matlab
开开心心就好18 分钟前
白天晚上自动调蓝光,护眼工具亮度可调
服务器·开发语言·算法·pdf·ocr·intellij-idea·idea
张张123y19 分钟前
后端第十一课:RAG 落地实战(从 0 到 1 接上私有知识库,并设计一个好用的 RAG)
开发语言·人工智能·python·机器学习·fastapi·rag
梅梅绵绵冰21 分钟前
JVM虚拟机
java·开发语言·jvm
绛橘色的日落(。・∀・)ノ25 分钟前
C#学习笔记
笔记·学习·c#
asdzx6733 分钟前
C# 将 HTML 转换为 PDF:基于 Chrome 的转换方案
pdf·c#·html
Shaoshing1 小时前
消息顺序
java·开发语言
云水初1 小时前
【项目篇】基于LanGraph的自动处理客服邮件的 Agent汇总
开发语言·笔记·python·学习·fastapi·langgraph
茉莉玫瑰花茶1 小时前
GO [ 内存与变量逃逸分析 ]
开发语言·后端·golang
lhh_qrsly1 小时前
OTA 加密完整方案(嵌入式 IoT 常用)
开发语言·物联网·php