在沒有使用反射之前,跨項目級的呼叫普遍的做法是項目級添加引用。
舉例:Client 類別呼叫 MysqlHelper 類別的話
介面類別 DbHelper.cs
using System; namespace IHelper { public class DbHelper { public DbHelper() { Console.WriteLine("This is DbHelper construction"); } public virtual void Query() { Console.WriteLine("This is query method"); } } }
OracleDbHelper.cs
using System; using IHelper; namespace OracleHelper{ public class OracleDbHelper : DbHelper { public override void Query() { base.Query(); Console.WriteLine("This is query from OracleDbHelper"); } } }
MySqlDbHelper.cs
using System; using IHelper; namespace MySqlHelper{ public class MySqlDbHelper :DbHelper { public override void Query() { base.Query(); Console.WriteLine("This is query method from MySqlDbHelper"); } } }
Client 端Program.cs 調用:端的資料庫幫助目錄然後在App.config 裡面增加配置,接著使用Reflection 下的Assembly 類別去實作。
Program.cs
static void Main(string[] args){ string config = ConfigurationSettings.AppSettings["DbHelper"]; Assembly assembly = Assembly.Load(config.Split(',')[0]); Type typeHelper = assembly.GetType(config.Split(',')[1]); Object oHelper = Activator.CreateInstance(typeHelper); DbHelper dbHelper = (DbHelper) oHelper; dbHelper.Query(); Console.Read(); }
Client 端App.config 配置:
<?xml version="1.0" encoding="utf-8" ?><configuration> <startup> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" /> </startup> <appSettings> <!--<add key="DbHelper" value="MySqlHelper,MySqlHelper.MySqlDbHelper"/>--> <add key="DbHelper" value="OracleHelper,OracleHelper.OracleDbHelper"/> </appSettings></configuration>
以上是C# Reflection 反射的內容,更多相關內容,更多相關內容。 !