C# reflex mechanism

Posted by Dan The Man on Thu, 03 Mar 2022 15:13:08 +0100


Reflection is NET, through reflection, you can obtain the member and member information of each type (including class, structure, delegate, interface and enumeration) in the program or assembly at run time. With reflection, you can know every type like the back of your hand. In addition, I can create objects directly, even if the type of this object is not known at compile time.


1. You can use reflection to dynamically create instances of types, bind types to existing objects, or obtain types from existing objects;
2. The application needs to load a specific type from a specific assembly at runtime, so that reflection can be used when implementing a task;
3. Reflection is mainly applied to class libraries. These classes need to know the definition of a type in order to provide more functions
Reflection can obtain the information of the assembly or assembly, or dynamically load the assembly, create an instance of one type, and execute the methods in the instance.


(1) Use Assembly to define and load assemblies, load modules listed in the Assembly manifest, and find and create instances of types from this Assembly.
(2) Use Module to understand the assembly containing the Module and the classes in the Module. You can also obtain all global methods or other specific non global methods defined on the Module.
(3) Use ConstructorInfo to understand the name, parameters, access modifiers (such as pulic or private) and implementation details (such as abstract or virtual) of the constructor.
(4) Use MethodInfo to understand the name, return type, parameters, access modifiers (such as pulic or private) and implementation details (such as abstract or virtual) of the method.
(5) Use fieldinfo to understand the field name, access modifier (such as public or private) and implementation details (such as static), and get or set the field value.
(6) Use EventInfo to understand the event name, event handler data type, custom attribute, declaration type and reflection type, and add or remove event handlers.
(7) Use PropertyInfo to understand the name, data type, declaration type, reflection type and read-only or writable state of the property, and get or set the property value.
(8) Use ParameterInfo to understand the name, data type, input parameter or output parameter of the parameter, and the position of the parameter in the method signature.


System.Type - class -- Through this class, you can access information of any given data type
System.Reflection.Assembly -class -- It can be used to access information about a given assembly or to load the assembly into the program

System.Type class

System. The type class plays a central role in reflection. But it is an abstract base class. Type has a derived class corresponding to each data type. We use the methods, fields and properties of the object of this derived class to find all information about this type.

1. There are three common ways to get the Type reference of a given Type:

●use C# typeof operator.
    Type t = typeof(string);
●Use object GetType()method.
    string s = "grayworm";
    Type t = s.GetType(); 
●You can also call Type Static method of class GetType(). 
    Type t = Type.GetType("System.String");*

2. Attribute of type class

    Name Data type name
    FullName Fully qualified name of the data type(Include namespace name)
    Namespace Defines the namespace name of the data type
    IsAbstract Indicates whether the type is abstract
    IsArray   Indicates whether the type is an array
    IsClass   Indicates whether the type is a class
    IsEnum   Indicates whether the type is an enumeration
    IsInterface    Indicates whether the type is an interface
    IsPublic Indicates whether the type is public
    IsSealed Indicates whether the type is a sealed class
    IsValueType Indicates whether the type is a value type

3. Method of type class

    GetConstructor(), GetConstructors(): return ConstructorInfo Type, which is used to get the information of the constructor of this class
    GetEvent(), GetEvents(): return EventInfo Type, which is used to obtain the information of the event of this class
    GetField(), GetFields(): return FieldInfo Type, which is used to obtain the information of the field (member variable) of this class
    GetInterface(), GetInterfaces(): return InterfaceInfo Type, which is used to obtain the information of the interface implemented by this class
    GetMember(), GetMembers(): return MemberInfo Type, which is used to get the information of all members of this class
    GetMethod(), GetMethods(): return MethodInfo Type, which is used to get the information of the method of this class
    GetProperty(), GetProperties(): return PropertyInfo Used to get the type information of the class

4. Reflection in system Application of type class

using System;
using System.Reflection;
namespace TestCsharp
    class Contact
        // Read-only properties.  
        public string Name { get; private set; }
        public string Address { get; private set; }
        public string m_sMail;
        // Public constructor.  
        public Contact()
        public Contact(string contactName, string contactAddress)
            Name = contactName;
            Address = contactAddress;
        public void Print()
            Console.WriteLine("Name:" + Name + " Address:" + Address);
    class Program
        static void Main(string[] args)
            Contact pt = new Contact();
            Type t = pt.GetType();
            ConstructorInfo[] ci = t.GetConstructors();    //Gets all constructors of the class
            Console.WriteLine("1.View constructor in class:");
            Console.WriteLine("Constructor has"+ci.Length+"individual");
            int num = 0;
            foreach (ConstructorInfo c in ci) //Traverse each constructor
                ParameterInfo[] ps = c.GetParameters();    //Take out all parameters of each constructor
                foreach (ParameterInfo pi in ps)   //Traverse and print all parameters of the constructor
                    Console.Write(pi.ParameterType.ToString() + " " + pi.Name + ",");
                Console.WriteLine("This is the second" + num++ + "individual");
            Console.WriteLine("\n2.View properties in a class:");
            PropertyInfo[] pis = t.GetProperties();
            foreach (PropertyInfo pi in pis)
            Console.WriteLine("\n3.View in class public method:");
            MethodInfo[] mis = t.GetMethods();
            foreach (MethodInfo mi in mis)
                Console.WriteLine(mi.ReturnType + " " + mi.Name);
            Console.WriteLine("\n4.View in class pulic field:");
            FieldInfo[] fis = t.GetFields();
            foreach (FieldInfo fi in fis)
            Console.WriteLine("\n5.Dynamically generate objects with constructors:");
            Type[] tt = new Type[2];
            tt[0] = typeof(string);
            tt[1] = typeof(string);
            //Get constructor based on parameter type 
            ConstructorInfo ctInfo = t.GetConstructor(tt); 
            //Construct an Object array as the input parameter of the constructor 
            object[] obj = new object[2]{"Zhang San","Pudong, Shanghai"};   
            //Call constructor to generate object 
            object o = ctInfo.Invoke(obj);    
            //Call the method of the generated object to test whether the object generation is successful 
            Console.WriteLine("\n6.use Activator Build object:");//
            //Constructor parameters 
            object[] objs = new object[2] { "Li Si", "Beijing Wangfujing" };   
            //Use the static CreateInstance method of Activator to generate a new object 
            object ob = Activator.CreateInstance(t, objs);
            Console.WriteLine("\n7.Generate objects with reflection and call properties, methods and fields for operation:");  
            object obNew = Activator.CreateInstance(t);
            //Get m_sMail field 
            FieldInfo fi6 = t.GetField("m_sMail");
            //Give m_sMail field assignment 
            fi6.SetValue(obNew, "hawkitachi@gmail.com");
            //Get Name property 
            PropertyInfo pi6 = t.GetProperty("Name");
            //Assign a value to the MyName property 
            pi6.SetValue(obNew, "Wang Erma", null);
            PropertyInfo pInfo6 = t.GetProperty("Address");
            pInfo6.SetValue(obNew, "Nanjing, Jiangsu", null);
            //Get show method 
            MethodInfo mi6 = t.GetMethod("Print");
            //Call the show method 
            mi6.Invoke(obNew, null);

Output results


namespace ReflectionTest
    class ReflectionHelper
        public void InvokeMethod()
            #region method I
            Assembly assembly1 = Assembly.Load("ReflectionTest");
            Type type1 = assembly1.GetType("ReflectionTest.Person");
            object obj1 = System.Activator.CreateInstance(type1);
            MethodInfo method1 = type1.GetMethod("Show");
            method1.Invoke(obj1, null);

            #region method II
            object obj2 = Assembly.Load("ReflectionTest").CreateInstance("ReflectionTest.Person");
            Type type2 = obj2.GetType();
            MethodInfo method = type2.GetMethod("Show");
            method.Invoke(obj2, null);

Topics: C#