反射应用

1.通过反射实现多系统数据库的配置

通过定义接口,反射实例化配置的节点的值

配置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");
        }
    }
}

输出效果:

image

原文地址:https://www.cnblogs.com/keithmoring/p/4121386.html