您的位置:首页 > 编程语言 > C#

[Design Pattern] Generic Singleton Pattern with C#

2011-06-09 12:08 681 查看
using System;using System.Collections.Generic;using System.Text;using System.Reflection;namespace DesignPattern{    public class TSingleton<T> where T : class    {        static object SyncRoot = new object();        static T instance;        public static readonly Type[] EmptyTypes = new Type[0];         public static T Instance        {            get            {                if (instance == null)                {                    lock (SyncRoot)                    {                        if (instance == null)                        {                            ConstructorInfo ci = typeof(T).GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, null, EmptyTypes, null);                            if (ci == null) { throw new InvalidOperationException("class must contain a private constructor"); }                            instance = (T)ci.Invoke(null);                            //instance = Activator.CreateInstance(typeof(T)) as T;                        }                    }                }                return instance;            }        }    }}


public static readonly Type[] EmptyTypes = new Type[0];
这一行代码是很重要的!
在.NETCF中,Type.EmptyType并没有被声明,但在.NET中却有
而在我的项目中,这个单例的实践却是必须利用.NETCF的dll项目来实践出.NETCF与.NET通用的dll
因此有此行声明
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: