Reflection | assembly, reflection Program
What is assembly:
Assembly is. Net concepts. net dll and exe are both Assembly. Their difference is that exe can be executed directly (because it has the main function, but dll does not), and dll cannot be executed directly, it does not have an entry to the main function. It is called by other programs.
The console application is finally compiled into an exe file, and the library compilation generates a dll file
What is reflection:
Reflection is the process of dynamically loading an assembly, obtaining the type in the Assembly, creating an object, and calling its members through programming. This is reflection.
In solution 1, we first create a class library named "TestDll" as follows:
Using System; using System. collections. generic; using System. linq; using System. text; using System. threading. tasks; namespace TestDll {public class Person {public Person (string name, int age, string email) {this. name = name; this. age = age; this. email = email;} public Person () {} public string Name {get; set;} public int Age {get; set;} public string Email {get; set ;} public void Say () {Console. WriteLine ("Hi...");} public void SayHello () {Console. WriteLine ("Hi, I am SayHello, no parameter overload method! ");} Public void SayHello (string msg) {Console. writeLine (msg);} public int Add (int x, int y) {return x + y;} public interface IFlyable {void Fly ();} public class Student: person {} internal class Teacher: Person {} public class MyClass1: IFlyable {public void Fly () {Console. writeLine ("") ;}} public delegate void MyDelegate (); public struct MyStruct {} struct MyStruct1 {}}
2. Create a console application to practice how to use this reflection.
Using System; using System. collections. generic; using System. linq; using System. reflection; using System. text; using System. threading. tasks; namespace reflection {public class MyClass {public string Name {get; set;} public void Say () {Console. writeLine ("Hello ...... ");} private void SayHello () {Console. writeLine ("Hello everyone");} class Program {static void Main (string [] args) {// introduction to Type // 1. how to obtain a Type (that is: Original data of this Type), there are two methods // 1.1 when there is a Type object acquisition method MyClass mc = new MyClass (); Type t1 = mc. getType (); // in this way, the Type of the MyClass Type is obtained. // 1.2 only supports classes. If there is no Type object, Type t2 = typeof (MyClass ); // In this way, the Type of the MyClass Type is obtained. // --------------------- what can I do with this Type? ----------------------- // 1. Who is the parent class of the current type? Console. WriteLine (t1.BaseType. ToString (); // who is the parent class of the current type? // Console. writeLine (t1.BaseType. baseType. toString (); // 2 obtain all public fields of the current type FieldInfo [] fieldinfo = t1.GetFields (); // 3 get all public properties of the current type PropertyInfo [] propertyinfo = t1.GetProperties (); // 4 get all public methods of the current type MethodInfo [] methodinfo = t1.GetMethods (); // 5 obtain all public events of the current type EventInfo [] eventinfo = t1.GetEvents (); // 6 obtain all public constructors of the current type ConstructorInfo [] constructorinfo = t1.GetConstructors (); //................ and so on //-- ----------------------------------------- // Dynamically load an Assembly (the Assembly class represents an Assembly, which is an abstract class with some static members) // depending on the program path, dynamically load an Assembly asm = Assembly. loadFile (@ "D: \ learn \ Solution1 \ TestDll \ bin \ Debug \ TestDll. dll "); // obtain all types of Type [] types = asm. getTypes (); foreach (var v in types) {// Console. writeLine (v. fullName); // obtain the names of all types in the dataset and print the following output/* TestDll. person TestDll. IFlyable TestDll. student TestDll. teacher TestDl L. myClass1 TestDll. myDelegate TestDll. myStruct TestDll. myStruct1 * // We generally only get all public types in the Assembly (I .e., get all public types in the assembly) Type [] publicTypes = asm. getExportedTypes (); foreach (var v in publicTypes) {Console. writeLine (v. fullName); // print it to generate the following output/* TestDll. person TestDll. IFlyable TestDll. student TestDll. myClass1 TestDll. myDelegate TestDll. myStruct */} // ------- sometimes we only need to obtain a certain type. For example, we want to obtain this Person type ----------- -- // Type ptype = asm. getType ("TestDll. person "); // Note: The namespace TestDll of the Person class should be included in the brackets; that is, namespace + class name // ----------------- now let's call Say () in the Person class () method --------- // to call the Say () method in the Person class, obtain the Say () method MethodInfo methodA = ptype. getMethod ("Say"); // get the Say () method, and then we will call this Say () method .... how can I call it? // Methodinfo. the Invoke method is used to call the Say () method, but it has two parameters, // The first parameter: indicates the Class Object of the Say () method; because the Say () method is a non-static method, only the class object can call the non-static method. // The second parameter indicates the parameter of the Say () method, if there is no parameter, write null. Because a method can have multiple parameters, it is an array type of an object // The problem arises. Since we want to get the object of the class to which the Say () method belongs, we can also directly use the Person type method, so we cannot directly create a Person type object. We also use another method to create the Person type object objA = Activator. createInstance (ptype); // A methodA object of the Person class is created based on the ptype. invoke (objA, null); // the output of this Say method is called here: Hi ..... // --------------- now let's call the non-parameter overload method of SayHello () in the Person class ------------ // MethodInfo methodB = ptype. getMethod ("SayHello", new Type [] {}); // pay attention to the second parameter The number indicates the parameter of the SayHello () method, because the method can have multiple parameters. All the second parameters are an array, and I have not put anything in the array, put an empty array to obtain the SayHello () method object objB = Activator without parameters under the Person class. createInstance (ptype); methodB. invoke (objB, null); // -------------- now let's call SayHello () in the Person class to reload the method with one parameter --------- // MethodInfo methodC = ptype. getMethod ("SayHello", new Type [] {typeof (string)}); // get SayHello () This method has a string Type parameter method object objC = Activator. createInstance (ptype ); MethodC. invoke (objC, new object [] {"parameter 1"}); // output: parameter 1 // --------------------------- create an object -------------- through Type // we have created a Person-Type object objD = Activator based on the Type of Person. createInstance (ptype); // However, it is also a problem to create an object using the above method. Because if this Person has no constructor and only some constructor with parameters, I want to create an object by calling some constructor with parameters. In this case, Activator is used. createInstance (ptype); no, because Activator. createInstance (ptype) is to call the non-argument constructor to create an object. It does not specify the parameter constructor to create an object, therefore, we can create an object ---------/1 by calling the specified constructor. obtains the specified ConstructorInfo = ptype. getConstructor (new Type [] {typeof (string), typeof (int), typeof (string)}); // 2. call the constructor to create the object objE = info. invoke (new object [] {"James ", 25, "123@qq.com "}); // This objeE is the object created by specifying the constructor // obtain the attribute value of the specified object through radiation. For example, here I want to obtain the Name attribute value of the Person class // 1. first, obtain the Name attribute PropertyInfo pinfo = ptype under this Person class. getProperty ("Name"); string name = pinfo. getValue (objE, null ). toString (); // obtain the Name attribute value of the objE object Console. writeLine (name); // We can also set the attribute value pinfo. setValue (objE, ""); // you can specify the object Name attribute value string name2 = pinfo. getValue (objE, null ). toString (); Console. writeLine (Name2); // output the reset Name value // ------------------- IsAssignableFrom () of the Type class () method ------------------------- // check whether a class is another subclass Type typePerson = asm. getType ("TestDll. person "); Type typeStudent = asm. getType ("TestDll. student "); Type typeTeacher = asm. getType ("TestDll. teacher "); // indicates whether objects of the typeStudent type can be assigned to objects of the typePerson type (in fact, it is to check whether the Student class is a subclass of the Person class) bool p = typePerson. isAssignableFrom (typeStudent); Co Nsole. writeLine (p); // output: true bool s = typePerson. isAssignableFrom (typeTeacher); Console. writeLine (s); // output: true // indicates whether a typeStudent type object can be assigned to a typeTeacher type object bool t = typeTeacher. isAssignableFrom (typeStudent); Console. writeLine (t); // output; false // ------------------- IsInstanceOfType () method of the Type class --------------------------- // check whether an object is of a certain Type. createInstance (typePerson); // create Create a typePerson object objStudent = Activator. createInstance (typeStudent); // create a typeStudent type object objTeache = Activator. createInstance (typeTeacher); // create a typeTeacher type object // check whether objPerson is a TypePerson type object bool p1 = typePerson. isInstanceOfType (objPerson); Console. writeLine (p1); // output: true // check whether objStudent is a TypePerson type object bool s1 = typePerson. isInstanceOfType (objStudent); Console. writeLine (s1); // Output: true, because Student is a subclass of the Person class // check whether objTeache is a TypePerson-type object bool tt = typePerson. isInstanceOfType (objTeache); Console. writeLine (tt); // output: true, because Teache is a subclass of the Person class bool ts = typeTeacher. isInstanceOfType (objStudent); Console. writeLine (ts); // output False, because objStudent is not a Teacher instance // ----------------- IsSubclassOf () of the Type class () method ------------------------- // check whether a class is a subclass of another class (verify the parent-child relationship and it is not related to the interface) // check typePe Whether the rson class is a subclass of the typeStudent class (determine whether the class represented by System. Type is derived from the class represented by the specified System. Type .) Bool b1 = typePerson. isSubclassOf (typeStudent); Console. writeLine (b1); // output: false // check whether the typeStudent class is a subclass of the typePerson class bool b2 = typeStudent. isSubclassOf (typePerson); Console. writeLine (b2); // output: true // ------------------- IsSubclassOf () of the Type class () method ------------------------- // actually, it is used to determine whether a class is an abstract class. // check whether the Person class is an abstract class bool bb = typePerson. isAbstract; Console. writeLine (bb); // output: false Console. readKey ();}}}