Reflection (3) Reflection application: a plug-in project, plug-in Project
The previous section summarizes the use of reflection. This article combines a complete project to summarize the practical application of reflection.
Project Structure
For example:
Define plug-in Interface
In project ConsoleApplication6.IService, two interfaces are defined. Run represents driving, and Trun represents steering. The following code:
1 namespace ConsoleApplication6.IService 2 {3 /// <summary> 4 /// create an interface for a vehicle 5 /// </summary> 6 public interface ICarService 7 {8 // <summary> 9 // 10 // </summary> 11 void Run (); 12 13 /// <summary> 14 // Turn to 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}
Plug-in implementation
Here, two projects are created to implement plug-ins, ConsoleApplication6.Service. BMW and ConsoleApplication6.Service. BenZ. The Code is as follows:
1 namespace leleapplication6.service. BMW 2 {3 public class BMWCarService: ICarService 4 {5 /// <summary> 6 /// driving 7 /// </summary> 8 public void Run () 9 {10 Console. writeLine ("BMW Car Run! "); 11} 12 13 // <summary> 14 // turn to 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 leleapplication6.service. benZ 2 {3 public class BenZCarService: ICarService 4 {5 /// <summary> 6 /// driving 7 /// </summary> 8 public void Run () 9 {10 Console. writeLine ("BenZ Car Run! "); 11} 12 13 // <summary> 14 // turn to 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}
Run the program
Next, we can use reflection to run this plug-in program. The Code is as follows:
1 namespace ConsoleApplication6 2 {3 class Program 4 {5 static void Main (string [] args) 6 {7 var assembly = Assembly. load ("leleapplication6.service. BMW "); // You can also read 8 var t = assembly from the configuration file. getType ("leleapplication6.service. BMW. BMWCarService "); // You can also read 9 10 from the configuration file // create an instance of a car 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}
In this way, a simple plug-in program is completed. At the same time, if we develop a similar plug-in framework, reflection technology will be widely used.