publicstatic Singleton Instance { get { return Nested._instance; } }
privateclassNested { staticNested() { }
internalstaticreadonly Singleton _instance = new Singleton(); } }
版本 6
Lazy<T>默认的设置就是线程安全。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
publicclassSingleton { // 因为构造函数是私有的,所以需要使用lambda privatestaticreadonly Lazy<Singleton> _instance = new Lazy<Singleton>(() => new Singleton()); // new Lazy<Singleton>(() => new Singleton(), LazyThreadSafetyMode.ExecutionAndPublication);
publicabstractclassSingleton<T> whereT : class { privatestaticreadonly Lazy<T> _instance = new Lazy<T>(() => { var ctors = typeof(T).GetConstructors( BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public); if (ctors.Count() != 1) thrownew InvalidOperationException($"Type {typeof(T)} must have exactly one constructor."); var ctor = ctors.SingleOrDefault(c => !c.GetParameters().Any() && c.IsPrivate); if (ctor == null) thrownew InvalidOperationException( $"The constructor for {typeof(T)} must be private and take no parameters."); return (T)ctor.Invoke(null); });