.net 8 使用学习小记

单例模式
public class Singleton
{
    private static Singleton instance = null;
    private static readonly object syncRoot = new object();
 
    private Singleton() { }
 
    public static Singleton Instance
    {
        get
        {
            if (instance == null)
            {
                lock (syncRoot)
                {
                    if (instance == null)
                    {
                        instance = new Singleton();
                    }
                }
            }
 
            return instance;
        }
    }
}

这个实现使用了双重检查锁定(double-checked locking),以确保在多线程环境下也能高效安全地创建单例。首次检查instance == null是为了避免在单例已经被创建后的每次调用中都进行锁定,而内部的检查则确保了即使在多线程情况下只有一个实例被创建

代码优化

常规写法

FileStream? fs = null;
if (fs == null)
    fs = new FileStream("1.txt", FileMode.CreateNew, FileAccess.ReadWrite);

使用代码优化(复合分配)

FileStream? fs = null;
fs ??= new FileStream("1.txt", FileMode.CreateNew, FileAccess.ReadWrite);

内联变量声明

以前写法

Dictionary<string, string >  dic = new Dictionary<string, string>();

string? content = null;
dic.TryGetValue("aaa", out  content);

内联写法

Dictionary<string, string >  dic = new Dictionary<string, string>();

dic.TryGetValue("aaa", out string? content);

相关推荐

  1. .net 8 使用学习小记

    2024-03-21 06:24:02       23 阅读
  2. <span style='color:red;'>NAT</span><span style='color:red;'>小记</span>

    NAT小记

    2024-03-21 06:24:02      30 阅读
  3. 新手学习yolov8目标检测小记1

    2024-03-21 06:24:02       8 阅读
  4. Mybatis-Plus使用小记

    2024-03-21 06:24:02       36 阅读
  5. Linux 使用小记

    2024-03-21 06:24:02       41 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-03-21 06:24:02       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-03-21 06:24:02       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-03-21 06:24:02       19 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-03-21 06:24:02       20 阅读

热门阅读

  1. ucloud、阿里云、硅云的香港服务器哪家更好?

    2024-03-21 06:24:02       21 阅读
  2. Android studio添加阿里云仓库

    2024-03-21 06:24:02       22 阅读
  3. 3716. 命名法 北京师范大学考研机试题 模拟思想

    2024-03-21 06:24:02       18 阅读
  4. 【状态估计】概率论基础

    2024-03-21 06:24:02       20 阅读
  5. 王道c语言-队列顺序存储与链式存储

    2024-03-21 06:24:02       21 阅读
  6. 汇编LOG怎么看

    2024-03-21 06:24:02       20 阅读
  7. 前端小白的学习之路(ES6 一)

    2024-03-21 06:24:02       21 阅读
  8. 汇编语言中的MVC

    2024-03-21 06:24:02       16 阅读
  9. 用AI启动个人项目实战【连载03】

    2024-03-21 06:24:02       22 阅读