zoukankan      html  css  js  c++  java
  • 单例模式

    using System;
    using System.Linq;
    using System.Reflection;
    
    namespace DotnetSpider.Core.Infrastructure
    {
    	/// <summary>
    	/// 单独的泛型实型
    	/// </summary>
    	/// <typeparam name="T"></typeparam>
    	public abstract class Singleton<T>
    	{
    		private static readonly Lazy<T> MyInstance = new Lazy<T>(() =>
    		{
    			var ctors = typeof(T).GetConstructors(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
    			if (ctors.Length != 1)
    			{
    				throw new InvalidOperationException($"Type {typeof(T)} must have exactly one constructor.");
    			}
    			var ctor = ctors.SingleOrDefault(c => !c.GetParameters().Any() && c.IsPrivate);
    			if (ctor == null)
    			{
    				throw new InvalidOperationException($"The constructor for {typeof(T)} must be private and take no parameters.");
    			}
    			return (T)ctor.Invoke(null);
    		});
    
    		/// <summary>
    		/// 单例对象
    		/// </summary>
    		public static T Instance => MyInstance.Value;
    	}
    }
    

    源码

  • 相关阅读:
    word查找与替换
    细说ASP.NET Windows身份认证
    防钓鱼代码
    sql触发器
    url地址栏参数
    sql递归查询
    认识TWICImage类
    尝试发个贴
    泛型单元
    [学习官方例子]TArray
  • 原文地址:https://www.cnblogs.com/TTonly/p/11069872.html
Copyright © 2011-2022 走看看