首页 > Windows开发 > 详细

个人封装的C#单例基类

时间:2019-03-05 17:23:46      阅读:483      评论:0      收藏:0      [点我收藏+]
 /// <summary>
    /// 带接口的单例,通常用于可MOCK的类
    /// </summary>
    /// <typeparam name="T">单例的类型</typeparam>
    /// <typeparam name="I">单例类型的接口</typeparam>
    public class SingleInstance<T, I> where T : I
    {
        private static object lockObj = new object();
        private static T mySelf = default(T);
        public static I Instance
        {
            get
            {
#if DEBUG
                if (Mocking != null)
                    return Mocking;
#endif
                lock (lockObj)
                {
                    if (mySelf == null)
                    {
                        mySelf = InstanceCreater.CreateInstance<T>();
                    }
                }

                return mySelf;
            }
        }

#if DEBUG
        public static I Mocking { get; set; }
#endif

    }

    /// <summary>
    /// 单例,需要在当前类中定义
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class SingleInstance<T> where T : class
    {
        private static object lockObj = new object();
        private static T mySelf;//= default(T);
        public static T Instance
        {
            get
            {
                lock (lockObj)
                {
                    if (mySelf == null)
                    {
                        mySelf = InstanceCreater.CreateInstance<T>();
                    }
                }

                return mySelf;
            }
        }
#if MOCK
        public static void InstanceClear()
        {
           mySelf=null;
        } 
#endif
    } 

    static class InstanceCreater
    {
        public static T CreateInstance<T>()
        {
            var type = typeof(T);
            try
            {
                return (T)type.Assembly.CreateInstance(type.FullName, true, BindingFlags.NonPublic | BindingFlags.Instance, null, null, null, null);
            }
            catch (MissingMethodException ex)
            {
                throw new System.Exception(string.Format("{0}(单例模式下,构造函数必须为private)", ex.Message));
            }
        }
    }

 

个人封装的C#单例基类

原文:https://www.cnblogs.com/likg/p/10477882.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!