使用反射创建对象

通过使用反射创建对象,废话不多说直接上代码

using System.Reflection;
namespace  Factory
{
    public class DALFactory
    {
        static DALFactory()
        {
            Assembly assembly = Assembly.Load(StaticConstant.DALDllName);
            DALType = assembly.GetType(Constant.DALTypeName);
        }
        private static Type DALType = null;
        public static IBaseDAL CreateInstance()
        {
            return (IBaseDAL)Activator.CreateInstance(DALType);
        }

    }
}
Constant 类:
 private static string DALTypeDll = ConfigurationManager.AppSettings["DALTypeDll"];
        public static string DALDllName = DALTypeDll.Split(',')[1];
        public static string DALTypeName = DALTypeDll.Split(',')[0];

配置文件:

 <appSettings>
    <add key="DALTypeDll" value="程序集.BaseDAL,程序集"/>
  </appSettings>

 

特别注意:BaseDAL是继承IBaseDAL的
posted @ 2018-05-04 21:46  技术小代  阅读(121)  评论(0编辑  收藏  举报