#region using directives
using system;
using system.collections.generic;
using system.text;
using system.reflection;
#endregion
namespace genericssingleton
{
/// <summary>
/// 单例范型
/// </summary>
/// <typeparam name="t"></typeparam>
public class singleton<t>
{
private static t _instance;
public singleton()
{
}
public static t instance
{
get
{
if (_instance == null)
{
//获得实例,使用这个方法的前提是t要有公有的、无参数的构造函数
_instance = (t)system.activator.createinstance(typeof(t));
}
return _instance;
}
}
}
/// <summary>
/// 要实现单例的类
/// </summary>
public class foo
{
private int count = 0;
public int count
{
get
{
count++;
return count;
}
}
}
/// <summary>
/// 主函数
/// </summary>
class program
{
static void main(string[] args)
{
//连续调用三次如果值是递增的话说明三次调用都是同一个实例
console.writeline(singleton<foo>.instance.count);
console.writeline(singleton<foo>.instance.count);
console.writeline(singleton<foo>.instance.count);
console.readline();
}
}
}
新闻热点
疑难解答