转 Singleton clr via c#3

    /// <summary>
    /// 注意 只有在构造器没有副作用的时候才能使用这个技术
    /// </summary>
    class Singleton
    {
        private static Singleton _value = null;
        private Singleton() { }
        public static Singleton GetSingleton()
        {
            if (_value != null)
                return _value;
            Singleton temp = new Singleton();
            Interlocked.CompareExchange(ref _value, temp, null);
            return _value;
        }
    }

还有一种技术

Lazy<string> s = new Lazy<string>(() => DateTime.Now.ToString(), LazyThreadSafetyMode.PublicationOnly);

还有静态构造函数也是一种方式

原文地址:https://www.cnblogs.com/ly7454/p/5129267.html