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();
相关推荐
励志不掉头发的内向程序员1 小时前
【从零写一个CAD 03】三个 double 值得单独一个类吗:把视图变换抽成 View
开发语言·c++·qt·学习·系统架构
PHP实战开发录1 小时前
PHP接口大整数为什么变了
开发语言·php
临床数据科学和人工智能兴趣组4 小时前
在R语言中, 使用 as.factor() 函数转换数值型变量
开发语言·r语言
andyweike7 小时前
php笔记
开发语言·笔记·php
Circ.8 小时前
Python 调试 Litellm 本地大模型接口:模型列表与对话接口实操踩坑记录
开发语言·python
波力海苔夹心脆6759 小时前
C# 序列化与反序列化详解:System.Text.Json、Newtonsoft.Json、XmlSerializer 用法、特性选项与安全实践
经验分享·后端·c#·json·.net
现任明教教主~10 小时前
Thinkphp站群蜘蛛池SaaS系统YanyvSEO含多用户/积分/六大引擎计费/易支付对接
java·开发语言·spring
Zhou14113610 小时前
SpringSecurity_02_授权与高级功能
开发语言·python
码匠许师傅11 小时前
【C++三方组件】cpp-httplib:一个头文件起 HTTP 服务
开发语言·c++·http