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

推荐订阅源

V
V2EX
宝玉的分享
宝玉的分享
Jina AI
Jina AI
IT之家
IT之家
博客园 - Franky
MyScale Blog
MyScale Blog
Y
Y Combinator Blog
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
I
InfoQ
雷峰网
雷峰网
WordPress大学
WordPress大学
Microsoft Security Blog
Microsoft Security Blog
Google DeepMind News
Google DeepMind News
美团技术团队
S
SegmentFault 最新的问题
罗磊的独立博客
博客园 - 聂微东
大猫的无限游戏
大猫的无限游戏
H
Help Net Security
D
Docker
博客园 - 司徒正美
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
阮一峰的网络日志
阮一峰的网络日志
M
MIT News - Artificial intelligence

博客园 - 萝卜青菜

.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();
        }
    }
}