一、理论实例
1、动态载入DLL创建对象
var assembly = Assembly.LoadFrom("C:\\Binn\\Sample.dll"); var t = assembly.GetType("Sample.Report"); var report = (IReport)Activator.CreateInstance(t);
2、判断对象是否继承于某接口
Type t = typeof(ClsA).GetInterface("IB"); Console.Write(t==null);
二、应用场景
多库支持:一个程序的数据保存在两个库中,希望根据参数动态的创建数据库对象;
1、我们首先实现一个数据库接口
public interface IDatabase { DataTable Execute(string sql); }
2、创建继承该接口的数据库类
public class ArchiveDB : IDatabase { public DataTable Execute(string sql) { DataTable dt; var db = new SQLServer2000 {ConnStr = Blackice.Config.WebConfig.ArchiveDB}; db.Execute(sql, out dt); return dt; } }
public class CurrentDB :IDatabase { public DataTable Execute(string sql) { DataTable dt; var db = new SQLServer2000 { ConnStr = Blackice.Config.WebConfig.CurrentDB }; db.Execute(sql, out dt); return dt; } }
3、获取数据的示例
/// <summary> /// 获取数据 /// </summary> /// <param name="dbname">指定的数据库名称</param> /// <param name="condition">查询条件</param> /// <returns></returns> public DataTable GetDataTable(string dbname,string tableName, string condition) { //根据指定的dbname反射创建数据访问接口 var assembly = Assembly.LoadFrom(string.Format("{0}\\SqlHelper.dll", Blackice.Config.WebConfig.BinnPath)); var typeName = string.Format("SqlHelper.{0}", dbname); var t = assembly.GetType(typeName); var db = (IDatabase)Activator.CreateInstance(t); //获取数据 var dt = db.Execute(string.Format("select * from {0} where prtNum='{1}'",tableName, condition)); return dt; }