/// <summary>
/// Singleton泛型类
/// </summary>
/// <typeparam name="T"></typeparam>
/// System.Threading.Interlocked.CompareExchange<T>(ref T, new T(), null);
/// 泛型约束:class:类型参数T必须为引用类型;new():为构造函数约束
public class Singleton<T> where T : class, new()
{
private static object lockHelper = new object();
private static T instance = null;//使用构造约束
public static T GetInstance()
{
if (instance == null)
{
lock (lockHelper)/加锁辅助对象
{
instance = new T();//构造约束
}
}
return instance;
}
}