cSharp:use Activator.CreateInstance with an Interface?

	///<summary>
	///数据访问工厂
	///生成時間2015-2-13 10:54:34
	///塗聚文(Geovin Du)
    /// (利用工厂模式+反射机制+缓存机制,实现动态创建不同的数据层对象接口)
	///</summary>
	public class AbstractFactory
	{


        protected static string path = ConfigurationManager.AppSettings["WebDAL"]; //"DAL";//生成的DLL文件名

        /// <summary>
        /// 数据库类型
        /// </summary>
        protected static string dalType
        {

            
            get
            {
                if (path.Contains("AccessDAL"))
                {
                    //path = "AcessDAL";                    
                    return "AccessDAL";
                }
                else if (path=="DAL")
                {
                   // path = "DAL";//生成的DLL文件名
                    return "SqlServerDAL";//命名空间名称
                }
                else if (path.Contains("MySQLDAL"))
                {
                    return "MySQLDAL";
                }
                else if (path.Contains("DALSQLite"))
                {
                    //path = "DALSQLite";
                    return "SQLiteDAL";
                }
                else if (path.Contains("PostgreSQLDAL"))
                {
                   // path = "DALPostgreSQL";
                    return "PostgreSQLDAL";
                }
                else if (path.Contains("OracleDAL"))
                {
                    return "OracleDAL";
                }
                else
                {
                    //path = "DAL";
                    return "SqlServerDAL";
                }
            }
        }

        public AbstractFactory()
        { }

		///<summary>
		///分页接口
		/// </summary>
		///<returns></returns>
		public static ISelectPage CreateSelectPage()
		{
			//ISelectPage page = new SelectPage();
			//return page;
            string className = "GeovinDu." + dalType + ".SelectPage";
            return (ISelectPage)Assembly.Load(path).CreateInstance(className); //命名空间名称GeovinDu.SqlServerDAL
            //path = "AcessDAL";//生成的DLL文件名

		}

		///<summary>
		///CompanyBranch接口
		/// </summary>
		///<returns></returns>
        public static ICompanyBranch CreateCompanyBranch(string _databaseprefix, string _sysdatarolefix)
		{
            //ICompanyBranch iCompanyBranch = new CompanyBranchDAL();
            //return iCompanyBranch;
            string className = "GeovinDu." + dalType + ".CompanyBranchDAL";//(_databaseprefix, _sysdatarolefix)
            return (ICompanyBranch)Assembly.Load(path).CreateInstance(className); //GeovinDu.SqlServerDAL
		}

		///<summary>
		///EnterpriseType接口
		/// </summary>
		///<returns></returns>
        public static IEnterpriseType CreateEnterpriseType(string _databaseprefix, string _sysdatarolefix)
		{
            //IEnterpriseType iEnterpriseType = new EnterpriseTypeDAL();
            //return iEnterpriseType;
            string className = "GeovinDu." + dalType + ".EnterpriseTypeDAL";
            return (IEnterpriseType)Assembly.Load(path).CreateInstance(className); 
		}

		///<summary>
		///LoginDiaryList接口
		/// </summary>
		///<returns></returns>
        public static ILoginDiaryList CreateLoginDiaryList(string _databaseprefix, string _sysdatarolefix)
		{
			//ILoginDiaryList iLoginDiaryList = new LoginDiaryListDAL();
			//return iLoginDiaryList;
            string className = "GeovinDu." + dalType + ".LoginDiaryListDAL";//(_databaseprefix, _sysdatarolefix)
            return (ILoginDiaryList)Assembly.Load(path).CreateInstance(className); 
		}

		///<summary>
		///OperatingUser接口
        ///https://msdn.microsoft.com/zh-cn/library/ms173128(VS.80).aspx   
        ///https://stackoverflow.com/questions/2202381/reflection-how-to-invoke-method-with-parameters
		/// </summary>
		///<returns></returns>
        public static IOperatingUser CreateOperatingUser(string _databaseprefix, string _sysdatarolefix)
		{
            //IOperatingUser iOperatingUser = new OperatingUserDAL(_databaseprefix, _sysdatarolefix);
			//return iOperatingUser;
            IOperatingUser iOperatingUser = null;
            string className = "GeovinDu." + dalType + ".OperatingUserDAL";//(_databaseprefix, _sysdatarolefix)
            //return (IOperatingUser)Assembly.Load(path).CreateInstance(className); 

            //string className = "GeovinDu.SQLiteDAL.OperatingUserDAL";
            //Assembly assembly = Assembly.LoadFrom(@"G:\winxp备份\PayrollPrint4\PayrollPrint\bin\Release\DALSQLite.dll");
            // object oo = assembly.CreateInstance(className);  //得到对象命名空间名
            // MethodInfo methodinfo = assembly.GetType("GeovinDu.GeovinDu.SQLiteDAL.OperatingUserDAL").GetMethod("OperatingUserDAL");   //得到方法
            //Object obj = methodinfo.Invoke(oo, new object[] { _databaseprefix, _sysdatarolefix });
            //IOperatingUser iOperatingUser = (IOperatingUser)obj;
            object obj = Assembly.Load(path).CreateInstance(className);
            Type t2 = obj.GetType();// Type.GetType("GeovinDu.SQLiteDAL.OperatingUserDAL", false, true);
            if (t2 != null)
            {
                iOperatingUser = (OperatingUserDAL)Activator.CreateInstance(t2, new object[] { });          //Assembly.Load(path).CreateInstance(className);  //值為空
            }

             //iOperatingUser = (IOperatingUser)Activator.CreateInstance(System.Type.GetType(className));


            return iOperatingUser;

		}

        ///<summary>
        ///PrintWordDocumentTemplateList接口
        /// </summary>
        ///<returns></returns>
        public static IPrintWordDocumentTemplateList CreatePrintWordDocumentTemplateList(string _databaseprefix, string _sysdatarolefix)
        {
            //IPrintWordDocumentTemplateList iPrintWordDocumentTemplateList = new PrintWordDocumentTemplateListDAL();
            //return iPrintWordDocumentTemplateList;
            string className = "GeovinDu." + dalType + ".PrintWordDocumentTemplateListDAL";//(_databaseprefix, _sysdatarolefix)
            return (IPrintWordDocumentTemplateList)Assembly.Load(path).CreateInstance(className); 
        }
       
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public static ISysConfig CreateSysConfig()
        {

            string className = "GeovinDu." + dalType + ".SysConfigDAL";
            return (ISysConfig)Assembly.Load(path).CreateInstance(className); 
            //databaseprefix = _databaseprefix;
            //ISysConfig iSysConfig = new DAL.SysConfigDAL();
            //return iSysConfig;
        }
	}

  

https://github.com/fabriciorissetto/CustomActivator

https://www.codeproject.com/Articles/55710/Reflection-in-NET

https://www.codeproject.com/Articles/14593/A-General-Fast-Method-Invoker

 https://github.com/ekonbenefits/impromptu-interface

 https://www.codeproject.com/Articles/109868/General-DynamicObject-Proxy-and-Fast-Reflection-Pr

https://www.codeproject.com/articles/15089/an-abstract-factory-using-app-config-and-reflectio

 https://www.microsoft.com/net/download/windows

 

 

        /// <summary>
        /// 无构造函数的用法
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dllname"></param>
        /// <param name="fullClassName"></param>
        /// <returns></returns>
        public static T CreateInstance<T>(string dllname, string fullClassName)
        {
            //string fullClassName = nameSpace + "." + className;
            return (T)Assembly.Load(dllname).CreateInstance(fullClassName);
        }
        /// <summary>
        /// 有構造函數的用法
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dllname"></param>
        /// <param name="fullName"></param>
        /// <param name="parameters">构造函数的参数</param>
        /// <returns></returns>
        public static T CreateInstance<T>(string dllname, string fullName, object[] parameters)
        {
            try
            {
                //string fullName = nameSpace + "." + className;//命名空间.类型名
                object ect = Assembly.Load(dllname).CreateInstance(fullName, true, System.Reflection.BindingFlags.Default | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, parameters, null, null);//加载程序集,创建程序集里面的 命名空间.类型名 实例
                return (T)ect;//类型转换并返回
            }
            catch
            {
                //发生异常,返回类型的默认值
                return default(T);
            }
        }
        /// <summary>
        /// 有構造函數的用法
        /// geovindu
        /// 塗聚文 涂聚文
        /// Geovin Du
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="fullTypeName"></param>
        /// <param name="paramArray">构造函数的参数</param>
        /// <returns></returns>
        public static T CreateInstance<T>(string fullTypeName, object[] parameters)
        {
            return (T)Activator.CreateInstance(Type.GetType(fullTypeName), parameters);
        }
        /// <summary>
        /// 有構造函數的用法
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dllname"></param>
        /// <param name="fullTypeName"></param>
        /// <param name="paramArray"></param>
        /// <returns></returns>
        public static T CreateInstanceActivator<T>(string dllname, string fullTypeName, object[] paramArray)
        {
            Assembly tempAssembly = Assembly.Load(dllname);
            Type typeofControl = tempAssembly.GetType(fullTypeName);
            return (T)Activator.CreateInstance(typeofControl, paramArray);
        }
        /// <summary>
        /// 有構造函數的用法
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="fullTypeName"></param>
        /// <param name="paramArray"></param>
        /// <returns></returns>
        //public static T CreateInstance<T>(string fullTypeName, params object[] paramArray)
        //{
        //    return (T)Activator.CreateInstance(Type.GetType(fullTypeName), args: paramArray);
        //}
        /// <summary>
        /// 无构造函数的用法
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="fullTypeName"></param>
        /// <returns></returns>
        public static T CreateInstance<T>(string fullTypeName)
        {
            return (T)Activator.CreateInstance(Type.GetType(fullTypeName));
        }

  

  string dir = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
            string pdll = dir + @"\DALSQLite.dll";
            Type type = Type.GetType("System.String");
            object obj = Assembly.Load("DALSQLite").CreateInstance(className, true, System.Reflection.BindingFlags.Default | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, parameter, null, null);//className
            //构造函数
            
            Type t2 = obj.GetType();
            object oodu = Activator.CreateInstance(t2,parameter);
                //t2.GetConstructors
            if (oodu != null)
            {
                string du = oodu.ToString();
            }

            string[] str = { _databaseprefix, _sysdatarolefix };

            //Type type = Type.GetType("System.String");
            Assembly pluginAssembly = Assembly.LoadFrom(pdll);
            Type dynclasstype = pluginAssembly.GetType(className);

            Type[] pt = new Type[2];
            pt[0] = typeof(string);// typeof(string);
            pt[1] = typeof(string);//typeof(string);
            //object dynobj = Activator.CreateInstance(dynclasstype);//有構造函數不可以用
            object dynobj = Activator.CreateInstance(dynclasstype,parameter);
            if (dynobj != null)
            {
                dynobj.ToString();
                ConstructorInfo[] cinfos = dynclasstype.GetConstructors();// (pt);
                ConstructorInfo cinfo = cinfos[0];// dynclasstype.GetConstructor(pt);
                
                if (cinfo != null)
                {
                    string na = cinfo.Name;
                    ParameterInfo[] psci = cinfo.GetParameters();
                    foreach (ParameterInfo pici in psci)   //遍历并打印所该构造函数的所有参数
                    {
                       string nci=pici.ParameterType.ToString() + " :" + pici.Name + ",";
                    }

                }
            }

            Type classType = pluginAssembly.GetType(className);
            StringBuilder g = new StringBuilder();
            ConstructorInfo[] ci = t2.GetConstructors();    //获取类的所有构造函数
            foreach (ConstructorInfo c in ci) //遍历每一个构造函数
            {
                c.ToString();
                ParameterInfo[] ps = c.GetParameters();    //取出每个构造函数的所有参数
                foreach (ParameterInfo pi in ps)   //遍历并打印所该构造函数的所有参数
                {
                    g.Append(pi.ParameterType.ToString() + " :" + pi.Name + ",");
                }
                
            }

  

posted @ 2018-05-07 15:53  ®Geovin Du Dream Park™  阅读(554)  评论(1编辑  收藏  举报