反射:
常用于工厂,消除switch。
依赖注入(DependencyInjection):解决switch问题。原本需要专门的IoC容器提供,比如Spring.Net。简单的使用.Net技术“反射”既可以。
格式:
Assembly.Load(“程序集名称”).CreateInstance(“命名空间.类名称”)
UsingSystem.Reflection;
Demo1:
//常规写法
IUserresult=new SqlserverUser();
//反射写法
UsingSystem.Reflection;
IUserresult=(IUser)Assembly.Load(“当前程序集的名称”).CreateInstance(“当前命名空间.要实例化的类名”);
Demo2:
简单工厂
UsingSystem.Reflection;
UsingSystem.Configrantion;
classDataAccess
{
private static readonly string AssemblyName = "ConsoleApp2";
private static readonly string db = "SqlServer";
//private static readonly string db = "Access";
//配合App.Config使用
//private static readonly string db =ConfigurationSettings.AppSettings["DB"];
public static IUser CreateUser()
{
string className = AssemblyName + "." + db + "User";
return(IUser)Assembly.Load(AssemblyName).CreateInstance(className);
}
public static IAdminCreateAdmin()
{
IAdmin result = null;
switch (db)
{
case "SqlServer":
result = newSqlServerAdmin();
break;
case "Access":
result = new AccessAdmin();
break;
}
return result;
}