前面總結了反射的使用,這一篇結合一個完整的項目來總結下反射的實際應用。
項目結構
如:
定義外掛程式介面
在項目ConsoleApplication6.IService中,定義了兩個介面,Run代表行駛,Trun代錶轉向,如下代碼:
1 namespace ConsoleApplication6.IService 2 { 3 /// <summary> 4 /// 建立一個車的介面 5 /// </summary> 6 public interface ICarService 7 { 8 /// <summary> 9 /// 行駛10 /// </summary>11 void Run();12 13 /// <summary>14 /// 轉向15 /// </summary>16 /// <param name="direction"></param>17 void Turn(Direction direction);18 19 }20 21 public enum Direction22 {23 East,24 Weast,25 South,26 North27 }28 }
外掛程式程式實現
這裡建立了兩個項目分別實現外掛程式程式,分別是ConsoleApplication6.Service.BMW和ConsoleApplication6.Service.BenZ,代碼如下:
1 namespace ConsoleApplication6.Service.BMW 2 { 3 public class BMWCarService: ICarService 4 { 5 /// <summary> 6 /// 行駛 7 /// </summary> 8 public void Run() 9 {10 Console.WriteLine("BMW Car Run!");11 }12 13 /// <summary>14 /// 轉向15 /// </summary>16 /// <param name="direction"></param>17 public void Turn(Direction direction)18 {19 Console.WriteLine(string.Format("BMW Car turn:{0}", direction.ToString()));20 }21 }22 }
1 namespace ConsoleApplication6.Service.BenZ 2 { 3 public class BenZCarService: ICarService 4 { 5 /// <summary> 6 /// 行駛 7 /// </summary> 8 public void Run() 9 {10 Console.WriteLine("BenZ Car Run!");11 }12 13 /// <summary>14 /// 轉向15 /// </summary>16 /// <param name="direction"></param>17 public void Turn(Direction direction)18 {19 Console.WriteLine(string.Format("BenZ Car turn:{0}", direction.ToString()));20 }21 }22 }
運行程式
接下來我們就可以利用反射來運行這個外掛程式程式了,如下代碼:
1 namespace ConsoleApplication6 2 { 3 class Program 4 { 5 static void Main(string[] args) 6 { 7 var assembly = Assembly.Load("ConsoleApplication6.Service.BMW");//也可以從設定檔中讀取 8 var t = assembly.GetType("ConsoleApplication6.Service.BMW.BMWCarService");//也可以從設定檔中讀取 9 10 //建立一輛車的執行個體11 var obj = Activator.CreateInstance(t);12 ICarService car = obj as BMWCarService;13 if (car != null)14 {15 car.Run();16 car.Turn(Direction.East);17 }18 19 Console.ReadKey();20 }21 }22 }
這樣,一個簡單的外掛程式程式就完成了,同時,如果我們開發類似的外掛程式架構,就會大量使用到反射技術。