using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

    
public static class SingletonProvider<T> where T : new()
    {
        
private static T m_instance;
        
private static readonly object sync = new object();
        
#region 无够构造函数的泛型单列
        
/// <summary>
        
/// 无够构造函数的泛型单列
        
/// </summary>
        public static T Instance
        {
            
get
            {
                
if (m_instance == null)
                {
                    
lock (sync)
                    {
                        
if (m_instance == null)
                        {
                            
try
                            {
                                m_instance 
= new T();
                            }
                            
catch
                            {
                            }
                        }
                    }
                }
                
return m_instance;
            }
        }
        
#endregion
        
#region 带构造函数的泛型单列模式
        
/// <summary>
        
/// 带构造函数的泛型单列模式
        
/// </summary> 
        public static T InstanceForParameter(params object[] objarr)
        {

            
if (m_instance == null)
            {
                
lock (sync)
                {
                    
if (m_instance == null)
                    {
                        var t 
= typeof(T);
                        var tp 
= new Type[objarr.Length];
                        
for (int i = 0; i < objarr.Length; i++)
                        {
                            tp[i] 
= objarr[i].GetType();
                        }
                        
try
                        {
                            System.Reflection.ConstructorInfo ci 
= t.GetConstructor(tp);
                            m_instance 
= (T)ci.Invoke(objarr);
                        }
                        
catch
                        {
                        }

                    }
                }
            }
            
return m_instance;
        } 
        
#endregion
    }

相关文章:

  • 2022-12-23
  • 2021-12-08
  • 2021-08-21
  • 2021-08-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-02-10
  • 2022-02-17
  • 2021-12-20
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案