The former summarizes the use of reflection, which combines a complete project to summarize the actual application of the reflection.
Project structure
Such as:
Defining plug-in interfaces
In the project Consoleapplication6.iservice, two interfaces are defined, the run represents the drive, the Trun represents the steering, and the following code:
1 namespace Consoleapplication6.iservice 2 {3//<summary> 4/// Create an interface for a car 5// </summary> 6
public Interface Icarservice 7 {8//<summary> 9//Travel// </summary>11 void Run ();///<SUMMARY>14///</summary>16// <param name= "direction" > </param>17 void Turn (Direction Direction);}20 public enum Direction22 { east,24 weast,25 south,26 North27 }28}
Plug-in program implementation
Here are two new projects implemented plug-in programs, respectively, ConsoleApplication6.Service.BMW and ConsoleApplication6.Service.BenZ, the code is as follows:
1 namespace ConsoleApplication6.Service.BMW 2 {3 Public class Bmwcarservice:icarservice 4 {5// <summa Ry> 6// /Travel 7 //</summary> 8 public void Run () 9 { Console.WriteLine ("BMW Car run!"); }12//<SUMMARY>14///</summary>16// <param name= "direction ></param>17 public void Turn (Direction Direction), { Console.WriteLine (string. Format ("BMW Car turn:{0}", direction. ToString ())); }21 }22}
1 namespace ConsoleApplication6.Service.BenZ 2 {3 Public class Benzcarservice:icarservice 4 {5// <sum Mary> 6/// Travel 7 //</summary> 8 public void Run () 9 { Console.WriteLine ("BenZ Car run!") ;}12//<summary>14//to </SUMMARY>16/// <param name= " Direction "></param>17 public void Turn (Direction direction) * { Console.WriteLine ( String. Format ("BenZ Car turn:{0}", direction. ToString ())); }21 }22}
Run the program
Then we can use the reflection to run the plug-in, the following code:
1 namespace ConsoleApplication6 2 {3 class program 4 {5 static void Main (string[] args) 6 {7 var as sembly = Assembly.Load ("ConsoleApplication6.Service.BMW");//You can also read 8 var t = Assembly from the configuration file. GetType ("ConsoleApplication6.Service.BMW.BMWCarService");//You can also read from the configuration file 9 //Create an instance of a car each var obj = Activator.CreateInstance (t); icarservice car = obj as bmwcarservice;13 if (car ! = null) Run (), car. Turn (direction.east); }18 Console.readkey (); }21 }22}
In this way, a simple plug-in program is completed, and if we develop a similar plug-in framework, it will be heavily used in the reflection technology.