一、格式:
Assembly.Load("程序集名称").CreateInstance("命名空间.名称")
程序集:创建类库的名称
命名空间:
二、反射解析
using System.Reflection;
三、实例demo
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Reflection;//引用反射 using System.Configuration;//配置文件 namespace ITOO_DAL { class DataAccess { //给变量字段赋值,读取配置文件中的值,只读 private static readonly string db = ConfigurationManager.AppSettings["DB"];//读取配置文件 //确定程序集名称,只读 private static readonly string AssemblyName = "ITOO_DAL"; //给程序集赋值 private static readonly string db = "Sqlserver"; //通过接口,反射创建User类 public static IUser CreateUser() { string className = AssemblyName + "." +db+ "User";//ITOO_DAL.User return (IUser) Assembly.Load(AssemblyName).CreateInstance(className); } //通过接口,反射创建department类 public static IDepartment CreateDepartment() { string className = AssemblyName + "." + db + "Department"; return (IDepartment) AssemblyName.Load(AssemblyName).CreatInstance(className); } } }
配置文件需要给DB赋值
<?xml version="1.0" encoding="utf-8" ?> <configuration> <startup> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" /> </startup> <!--给程序里面的变量赋值--> <appSettings> <add key="DB" value="Sqlserver"/> </appSettings> </configuration>
四、优点
让类的实例化变的更加灵活,代码解耦和。