C#反射应用实例

本文实例讲述了C#反射应用。分享给大家供大家参考。具体如下:

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

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

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

        }

    }

}

以上是 C#反射应用实例 的全部内容, 来源链接: utcz.com/z/321102.html

回到顶部