前面总结了反射的使用,这一篇结合一个完整的项目来总结下反射的实际应用。
如下图:
在项目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中文网其他相关文章!