标签:
1.采用配置文件使用反射
2. 配置文件 App.config
<?xml version="1.0" encoding="utf-8" ?> <configuration> <startup> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/> </startup> <appSettings>
<!--<add key="IHelpConfig" value="Com.Meteor.Dal,Com.Meteor.Dal.SqlserverHelper"/>-->
<add key="IHelpConfig" value="Com.Meteor.MySql,Com.Meteor.MySql.MysqlHelper"/>
</appSettings> </configuration>
3.反射举例
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Reflection; using Com.Meteor.Interface; using System.Configuration; namespace MyReflection { /// <summary> /// metadata元数据 /// </summary> class Program { static void Main(string[] args) { Console.WriteLine("欢迎大家来流星小子博客,学习反射技术"); // SqlserverHelper sqlserverHelper = new SqlserverHelper(); // sqlserverHelper.Query(); Console.WriteLine("-----------可配置可扩展--------------"); string iHelperConfig = ConfigurationManager.AppSettings["IHelpConfig"]; Assembly assembly = Assembly.Load(iHelperConfig.Split(‘,‘)[0]);//动态加载dll Type typeHelper = assembly.GetType(iHelperConfig.Split(‘,‘)[1]); Object oHelper = Activator.CreateInstance(typeHelper); IHelper iHelper = (IHelper)oHelper; //这句有性能损失,使用了强制类型转换 iHelper.Query(); Console.Read(); } } }
namespace Com.Meteor.Interface { public interface IHelper { void Query(); } } namespace Com.Meteor.Dal { public class SqlserverHelper : IHelper { public SqlserverHelper() { Console.WriteLine("这里开始构造SqlserverHelper"); } public void Query() { Console.WriteLine("SqlserverHelper Query"); } } }
public class MysqlHelper : IHelper { public MysqlHelper() { Console.WriteLine("这里开始构造MysqlHelper"); } public void Query() { Console.WriteLine("MysqlHelper Query"); } }
代码下载路径:https://i.cnblogs.com/Files.aspx
标签:
原文地址:http://www.cnblogs.com/gylhaut/p/5778033.html