.net 8 使用学习小记

本文介绍了Java中单例模式的双重检查锁定实现,以确保在多线程环境下的线程安全。同时,讨论了代码优化技巧,如复合分配和内联变量声明,以提高性能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

单例模式
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);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

破浪征程

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值