目录
一.引言
在C#中需要批量创生单例类时,一个个的写类实在时太累了.于是为了省力,我们要写一个父类,当继承了这个父类就可以成为单例类.
二.代码样例
using System;
using System.Collections;
using System.Collections.Generic;
public class Singleton<T> where T : Singleton<T>,new()
{ //static前缀使得可以通过类名.属性名来访问该属性
private static T instance = null;
public static T Instance
{ //只有get方法没有set方法,意味Instance对其他类为只读
get
{ //如果instance为空,则重新初始化instance为指向T类实例的指针
if (instance == null)
{
instance = new T();
}
//否则返回唯一的instance属性
return instance;
}
}
}
1.where说明:
public class Singleton<T> where T : Singleton