前面總結了反射的使用,這篇結合一個完整的項目來總結下反射的實際應用。
如下圖:
#
在專案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 }
這樣,一個簡單的插件程式就完成了,同時,如果我們開發類似的插件框架,就會大量使用到反射技術。
以上是總結反射技術的實際應用。的詳細內容。更多資訊請關注PHP中文網其他相關文章!