[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
因此有此行声明
相关文章推荐
- Implementing the Singleton Pattern in C#
- Implementing the Singleton Pattern in C#
- Using C# 2.0 Generics to achieve a reusable Singleton pattern
- Implementing the Singleton Pattern in C#
- A Generic Singleton Form Provider for C#
- 【转】单体模式-经典实现 Implementing the Singleton Pattern in C#
- Book Contents Reviews Notes Errata Articles Talks Downloads Resources Code Formatter Cover of C# in Depth Order now (3rd edition) Implementing the Singleton Pattern in C#
- A simple C# generic singleton class
- C# Singleton Pattern Demo
- Implementing the Singleton Pattern in C#
- Singleton Pattern in C# 5种实现
- Implementing the Singleton Pattern in C#[转载]
- SingleTon Pattern in C#.net
- [置顶] 设计模式之单例模式 (Design patterns of the The singleton pattern)c#
- Implementing the Singleton Pattern in C#
- Implementing the Singleton Pattern in C#
- Design Pattern学习(C#) ---- Singleton
- C# Singleton Pattern Versus Static Class
- A simple C# generic singleton class
- 设计模式之单例模式 (Design patterns of the The singleton pattern)c#