C# 简单的泛型单例
2016-01-14 10:30
260 查看
//SharedInstance.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SharedInstance { public class SharedInstance<T> where T:new() { private static T m_Instance = default(T); public static T Instance { get { if (m_Instance == null) { m_Instance = new T(); } return m_Instance; } } } }
这里使用了 Where 约束
使用Where 约束,new()约束 让编译器知道,提供的任何类型参数都具有默认构造函数。
也只有加了这个约束之后,才能使用 new T() ;
使用方法
//Student.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SharedInstance
{
public class Student:SharedInstance<Student>
{
public void GetAge()
{
Console.WriteLine("12");
}
}
}
//Program.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SharedInstance { class Program { static void Main(string[] args) { Student.Instance.GetAge(); Student.Instance.GetAge(); } } }
示例下载: http://pan.baidu.com/s/1gdP01J9
相关文章推荐
- C#引用dll库失败
- c#范型List的Sort方法详解
- 输出字符串中最长的单词 C# 算法
- C# Excel写入
- C# WebBrowser控件 模拟登录 抓取数据
- 运用VC#编程通过OPC方式实现PC机与西门子PLC通讯《异步篇》
- 运用VC#编程通过OPC方式实现PC机与西门子PLC通讯《异步篇》
- 用 C# 实现带键值的优先队列
- C# partial 说明
- C#图片验证码,旋转文字主要代码
- 利用C#开发web应用程序时,对注册表进行操作提示没有权限的解决办法
- C# 发送邮件
- C# event线程安全
- 【NCRE】——C#查看PowerPoint属性
- C# Graphics 放大和旋转
- C#中的单例模式
- C#位操作(转)
- C#:文件、路径(Path_File)
- C#学习(7):检测代码执行时间
- GridControl 中ComoboxEdit 列 模糊音查询