惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

博客园_首页
GbyAI
GbyAI
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Apple Machine Learning Research
Apple Machine Learning Research
大猫的无限游戏
大猫的无限游戏
阮一峰的网络日志
阮一峰的网络日志
Last Week in AI
Last Week in AI
V
Visual Studio Blog
酷 壳 – CoolShell
酷 壳 – CoolShell
The Cloudflare Blog
博客园 - 【当耐特】
博客园 - 叶小钗
量子位
博客园 - 聂微东
S
SegmentFault 最新的问题
美团技术团队
Hugging Face - Blog
Hugging Face - Blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
月光博客
月光博客
宝玉的分享
宝玉的分享
小众软件
小众软件
罗磊的独立博客
有赞技术团队
有赞技术团队
Stack Overflow Blog
Stack Overflow Blog

博客园 - 萝卜青菜

.Net2.0在程序中编译代码 - 萝卜青菜 - 博客园 C#利用VB的My功能来显示文件拷贝、删除、移动进度 - 萝卜青菜 - 博客园 .net2.0提供的TextBox候选文字提示功能 .net2.0轻松判断NumLock、CapsLock、ScrollLock、Insert键的状态:) .net2.0轻松取得应用程序图标 利用System.Media来做声音提醒 .net2.0窗体关闭时自动保存窗体位置及大小 .net2.0中改变数组大小 将窗体或窗体上某控件保存为图片 让窗体关闭按钮无效新法 ClickOnce部分信任文件达到一定大小怎么办?(技巧) 页面根据不同Url显示不同Title以及不同的Mete 新增的Application.OpenForms属性 全屏显示一个图片文件 新的两道面试题(简单) 求问模式达人,静态类可否代替单件? 使Div内内容可编辑:) GridView&DetailsView对XML文件增删改 对象池及数据库连接对象池
使用静态类来简化单件
萝卜青菜 · 2006-07-13 · via 博客园 - 萝卜青菜

呵呵,看图看代码说话:) 可能我也是错的。

using System;
using System.Collections.Generic;
using System.Text;using System.Reflection;namespace Singleton
{
    
static class Singleton<T> where T : classnew()
    {
        
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();
        }
    }
}