C#反射应用实例
这篇文章主要介绍了C#反射应用,实例分析了通过反射实现多系统数据库的配置方法,是比较实用的技巧,需要的朋友可以参考下
本文实例讲述了C#反射应用。分享给大家供大家参考。具体如下:
通过反射实现多系统数据库的配置
通过定义接口,反射实例化配置的节点的值
配置App.config:
1 <?xml version="1.0" encoding="utf-8" ?> 2 <configuration> 3 <appSettings> 4 <add key="DAL" value="FactoryInterface.Oracle"/> 5 </appSettings> 6 </configuration>
通过System.Configuration.ConfigurationManager.AppSettings读取该key的value,使用Configuration需要将其dll添加到项目中
接口定义:
1 namespace FactoryInterface 2 { 3 interface IDAL 4 { 5 void insert(); 6 } 7 }
Program定义:
1 namespace FactoryInterface 2 { 3 class Program 4 { 5 static void Main(string[] args) 6 { 7 8 string config = System.Configuration.ConfigurationManager.AppSettings["DAL"]; 9 Console.WriteLine(config); 10 Type t = Type.GetType(config); 11 IDAL dal =(IDAL) System.Activator.CreateInstance(t); 12 dal.insert(); 13 Console.ReadKey(); 14 15 } 16 17 } 18 class MySql : IDAL { 19 public void insert() { 20 Console.WriteLine("this data insert by MySql"); 21 } 22 } 23 class Oracle : IDAL 24 { 25 public void insert() 26 { 27 Console.WriteLine("this data insert by Oracle"); 28 } 29 } 30 }
输出效果如下图所示:

希望本文所述对大家的C#程序设计有所帮助。

浙公网安备 33010602011771号