通過定義接口,反射實例化配置的節(jié)點的值
配置App.config,(關于APP.config的配置有一篇博文很豐富,參見周公博客)
<?xml version="1.0" encoding="utf-8" ?><configuration> <appSettings> <add key="DAL" value="FactoryInterface.Oracle"/> </appSettings></configuration>
通過System.Configuration.ConfigurationManager.AppSettings讀取該key的value,使用Configuration需要將其dll添加到項目中
接口定義
namespace FactoryInterface{ interface IDAL { void insert(); }}
PRogram定義
namespace FactoryInterface{ class Program { static void Main(string[] args) { string config = System.Configuration.ConfigurationManager.AppSettings["DAL"]; Console.WriteLine(config); Type t = Type.GetType(config); IDAL dal =(IDAL) System.Activator.CreateInstance(t); dal.insert(); Console.ReadKey(); } } class MySQL : IDAL { public void insert() { Console.WriteLine("this data insert by MySql"); } } class Oracle : IDAL { public void insert() { Console.WriteLine("this data insert by Oracle"); } }}
輸出效果:

新聞熱點
疑難解答