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