








呵呵,看图看代码说话:) 可能我也是错的。
using System;
using System.Collections.Generic;
using System.Text;using System.Reflection;namespace Singleton
{
static class Singleton<T> where T : class, new()
{
static Singleton()
{ }public static readonly T Instance = Activator.CreateInstance<T>();
}
}
测试类,我想创建谁的单件就创建谁的单件。(说的夸张了点)
using System;
using System.Collections.Generic;
using System.Text;namespace Singleton
{
class Test
{
private int nCount;public Test()
{
nCount = 0;
}public void RecordCount()
{
nCount++;
}public void Display()
{
Console.WriteLine(nCount);
}
}
}
测试代码:
using System;
using System.Collections.Generic;
using System.Text;namespace Singleton
{
class Program
{
static void Main(string[] args)
{
Test test1 = Singleton<Test>.Instance;
test1.RecordCount();
test1.Display();
Test test2 = Singleton<Test>.Instance;
test2.RecordCount();
test2.Display();
Console.WriteLine(test1 == test2);
Console.Read();
}
}
}
此内容由惯性聚合(RSS阅读器)自动聚合整理,仅供阅读参考。 原文来自 — 版权归原作者所有。