C#-懒汉单例创建

作者 : admin 本文共577个字,预计阅读时间需要2分钟 发布时间: 2024-06-16 共1人阅读

文章速览

  • 概述
  • 直上代码

坚持记录实属不易,希望友善多金的码友能够随手点一个赞。
共同创建氛围更加良好的开发者社区!
谢谢~

概述

懒汉单例的创建模式,需要创建的单例直接继承该类即可。

直上代码


    public abstract class SingletonBase<T>
        where T : class
    {
        /// 
        /// Static instance. Needs to use lambda expression
        /// to construct an instance (since constructor is private).
        /// 
        private static readonly Lazy<T> sInstance = new Lazy<T>(() => CreateInstanceOfT());

        /// 
        /// Gets the instance of this singleton.
        /// 
        public static T Instance
        {
            get { return sInstance.Value; }
        }

        /// 
        /// Creates an instance of T via reflection since T's constructor is expected to be private.
        /// 
        /// T.
        private static T CreateInstanceOfT()
        {
            return Activator.CreateInstance(typeof(T), true) as T;
        }
    }
本站无任何商业行为
个人在线分享 » C#-懒汉单例创建
E-->