2024-04-01 · C# 基础 · 学习笔记

静态类与静态成员

静态成员属于类而不是实例,所有实例共享同一份。静态类不能 new 实例化,只能通过类名访问。常见的静态类有 Console、Math、Convert。

自己的教训:在静态类里放可变字段(比如 static int count)在多线程环境下会出问题,因为所有线程都在改同一个值。需要用 lock 或者 Interlocked。静态构造函数在类第一次被访问时自动执行一次。

什么时候用静态?1) 无状态的工具方法(Math、StringHelper);2) 全局唯一的配置;3) 扩展方法。不要把有状态的业务逻辑写成静态的。

代码示例

// 静态类
public static class StringHelper
{
    // 静态字段
    public static int CallCount = 0;

    // 静态方法
    public static string Reverse(string s)
    {
        CallCount++;
        char[] arr = s.ToCharArray();
        Array.Reverse(arr);
        return new string(arr);
    }
}

// 静态构造函数(只执行一次)
public static class Config
{
    public static string AppName { get; }

    static Config()
    {
        AppName = "MyApp";
        Console.WriteLine("Config 初始化");
    }
}

// 使用
Console.WriteLine(StringHelper.Reverse("hello")); // olleh
Console.WriteLine(StringHelper.CallCount); // 1
Console.WriteLine(Config.AppName); // MyApp
学习小结:以上是我学习这个知识点时的笔记和心得。技术学习没有捷径,多写多练多踩坑,自然就掌握了。如果这篇笔记对你有帮助,欢迎继续看看其他文章。