首页 > Windows开发 > 详细

单例(c#)

时间:2017-01-07 01:30:02      阅读:182      评论:0      收藏:0      [点我收藏+]

直接上代码

 

using System;  
using System.Collections.Generic;  
using System.Text;  
using System.Reflection;

/// <summary>
/// 1.泛型
/// 2.反射
/// 3.抽象类
/// </summary>

// 单例模板
public abstract class Singleton<T> where T : Singleton<T>
{
     protected static T instance = null;
    
     protected Singleton() { }

    public static T Instance()
    {
         if (instance == null)
        {
              // 先获取所有非public的构造方法
            ConstructorInfo[] ctors = typeof(T).GetConstructors(BindingFlags.Instance | BindingFlags.NonPublic);
            // 从ctors中获取无参的构造方法
            ConstructorInfo ctor = Array.Find(ctors, c => c.GetParameters().Length == 0);
            if (ctor == null) throw new Exception("Non-public ctor() not found!");
              // 调用构造方法
             instance = ctor.Invoke(null) as T;
         }

         return instance;
        }
    }
}

// 例子
public class Manager : Singleton<Manager>
{
    private Manager(){}
    // .. todo
}

  

单例(c#)

原文:http://www.cnblogs.com/zoemei/p/6257903.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!