Reflection allows us to obtain the Assembly metadata during the compilation or runtime. through reflection, we can:
● Create an instance of the type
● Trigger Method
● Get attributes and field information
● Delayed binding
......
If reflection is used during compilation, you can obtain the assembly type in the following two ways:
1. Type Static Methods
Type type = type. GetType ("somenamespace. someclass ");
2. Use typeof
Type type = typeof (someclass );
If reflection is used at run time, the type can be obtained through the Assembly instance method at run time:
Type type = ASM. GetType ("somenamespace. someclass ");
Obtain reflection Information
There is such a class:
Public class student {public int ID {Get; set;} public string name {Get; set;} public float score {Get; set;} public student () {This. id =-1; this. name = string. empty; this. score = 0;} public student (int id, string name, float score) {This. id = ID; this. name = Name; this. score = score;} Public String displayname (string name) {return string. format ("Student name: {0}", name);} public void showscore () {console. writeline ("Student Score:" + this. score );}}
Obtain the reflection information as follows:
Static void main (string [] ARGs) {type = type. getType ("leleapplication1.student"); // type = typeof (student); console. writeline (type. fullname); console. writeline (type. namespace); console. writeline (type. name); // obtain the property propertyinfo [] props = type. getproperties (); foreach (propertyinfo prop in props) {console. writeline (prop. name);} // obtain method methodinfo [] Methods = type. getmethods (); foreach (methodinfo method in methods) {console. writeline (method. returntype. name); console. writeline (method. name);} console. readkey ();}
Delayed binding
In general, assigning a value to an object instance occurs during the compilation period, as follows:
Student stu = new Student();stu.Name = "somename";
For "delayed binding", assign a value to the object instance or call the method to obtain the Assembly, type, method, and attribute at runtime when it occurs.
// Obtain the runtime Assembly ASM = assembly. getexecutingassembly (); // obtain the type = ASM. getType ("leleapplication1.student"); // get the object instance at runtime object Stu = activator. createinstance (type); // obtain the method specified during running methodinfo method = type. getmethod ("displayname"); object [] parameters = new object [1]; Parameters [0] = "Darren"; // Method for triggering the runtime string result = (string) method. invoke (STU, parameters); console. writeline (result); console. readkey ();