The reflection is described in the previous article, the following is mainly about the actual use of some reflection.
By reflecting us, I can get the interface and also get the class that implements the interface, at which point the interface reference can access an instance of the implementation class.
I first defined an interface:
Public Interface IPerson { void SetName (string name); void SayHello (); }
To define a class implementation:
namespacepeople{ Public classPeople:iperson { Public stringName {Set; Get; } Public stringSex {Set; Get; } Public stringAge {Set; Get; } Publicpeople () {} PublicPeople (stringname) {Name=name; } Public voidSetName (stringname) {Name=name; } Public voidSayHello () {Console.WriteLine ("Hello everyone, I am:"+Name); } }}
Implemented by reflection:
namespaceconsoleapp1{classProgram {Static voidMain (string[] args) {IPerson IPerson=NULL; Assembly Assembly= Assembly.Load ("people"); Type[] Types=Assembly. GetTypes (); foreach(varTinchtypes) { if(T.getinterface ("IPerson") !=NULL) {IPerson=(IPerson) activator.createinstance (t); } } if(IPerson! =NULL) {IPerson. SetName ("Vidyut 厶"); IPerson. SayHello (); } console.readline (); } }}
C # Reflection and Reflection interface