This is the 9th day of my participation in the August More Text Challenge. For details, see:August is more challenging

Reflection in C#

Reflection is an important mechanism in.NET. Through reflection, you can get the interface, class, method, field, property, and other information inside an assembly such as *.exe or *.dll. You can also dynamically create an instance of a type and execute its methods. Reflection is the ability of a program to access, detect, and modify its own state or behavior. Assemblies contain modules, modules contain types, and types contain members. Reflection provides objects that encapsulate assemblies, modules, and types. You can use reflection to dynamically create instances of types, bind types to existing objects, or get types from existing objects. You can then call the methods of the type or access its fields and properties.

Get the type by reflection

Description: there are three types 1. The typeof a value is obtained by typeof

System.Type personType=typeof(Person);
System.Type heroType=typeof(Framework.Hero);
Copy the code

2. Obtain the type of the class corresponding to an object

Framework.hero dmxy =new Framework.hero();
System Type=dmxy.GetType();
Copy the code

3. Obtain the corresponding type from the class name string

System.Type strType =System.Type.GetType("Person");
System.Type strType =System.Type.GetType("Framework.Hero");
Copy the code

Type class

attribute

  • Name Indicates the Name of the data type
  • FullName Fully qualified name of the data type
  • Namespace Specifies the name of the Namespace that defines the data type
  • IsAbstract indicates whether the type IsAbstract
  • 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 common
  • IsSealed indicates whether the type IsSealed
  • IsValueType Indicates whether the type is a value type
  • BaseType Indicates the type of the parent class
  • AssemblyQualifiedName

Assemblies + + namespace name of the class | is the GetType (STR) in the string

    /// <summary>
    ///See what fields are in type
    /// </summary>
    private void ShowTypeField()
    {
        // Get the type
        Type heroType = typeof(Framework.Hero);
        // See the name of the type
        Console.WriteLine("Name:" + heroType.Name);
        // See the full name of the type
        Console.WriteLine("FullName:" + heroType.FullName);
        // View the assembly name
        Console.WriteLine("Assembly:" + heroType.Assembly);
        // Add the full assembly name
        Console.WriteLine("Ass-Name:" +heroType.AssemblyQualifiedName);
        // Get the superclass of this type
        Console.WriteLine("BaseType:" + heroType.BaseType.BaseType);

        Type equipTypeType = typeof(EquipType);
    }
Copy the code

methods

  • GetMember(),GetMember (); GetMember(); GetMember(); Use to get information about the class constructor
  • GetEvent(),GetEvents()

Returns type EventInfo, used to get information about events of this class

  • GetInterface(),GetInterfaces()

Returns the InterfaceInfo type used to get information about the interface implemented by the class

  • GetField(),GetFields()

Return type FieldInfo, used to get information about the fields (member variables) of the class

  • GetPropeerty(),GetProperties()

Returns the ProperyInfo type, used to get information about the properties of the class

  • GetMethod(),GetMethods()

Returns type MethodInfo, used to get information about the method of this class


The use of Reflection

Reflection has the following uses:

  • It allows you to view attribute information at run time.
  • It allows you to examine the various types in the collection and instantiate them.
  • It allows delayed binding of methods and properties.
  • It allows you to create new types at run time and then use those types to perform tasks.
type role
Assembly Defines and loads an assembly, loads the modules listed in the assembly manifest, and finds a type from this assembly and creates an instance of that type
Module Learn about the assembly that contains the module, the classes in the module, etc. You can also get all global methods defined on the module or other specific non-global methods
ConstructorInfo Learn about constructor names, parameters, access modifiers (such as public or private), and implementation details (such as abstract or Virtual). Use the GetConstructors or GetConstructor method of Type to call a particular constructor
MethodInfo Learn about the method’s name, return type, parameters, access modifiers (such as public or private), and implementation details (such as abstract or Virtual). Use the GetMethods or GetMethod method of Type to call a particular method
FieldInfo Learn the field name, access modifiers (such as public or private), implementation details (such as static), and get or set the field value
EventInfo Learn the event name, event handler data type, custom features, declaration type, reflection type, and so on, and add or remove event handlers
PropertyInfo Learn the property’s name, data type, declaration type, reflection type, read-only or writable state, etc., and get or set the property value
ParameterInfo Know the name of the parameter, the data type, whether the parameter is an input parameter or an output parameter, and the position of the parameter in the method signature, etc

BindingFlags

The function of BindingFlags is to get the type by permission

 MemberInfo[] memberInfo_12 = type.GetMembers(BindingFlags.NonPublic | BindingFlags.Public);
  MemberInfo[] memberInfo_13 = type.GetMembers(BindingFlags.NonPublic | BindingFlags.Instance);
  MemberInfo[] memberInfo_23 = type.GetMembers(BindingFlags.Public | BindingFlags.Instance);
Copy the code
combination meaning
BindingFlag.Public BindingFlags.Instance Specifies an instance member decorated by public
BindingFlag.Public -BindingFlags.Static Specifies a static member decorated by public
BindingFlag.NonPublic -BindingFlags.Instance Specifies the instance member of the private/ Protect /internal modifier
BindingFlag.NonPublic – BindingFlags.Static Specifies static members with private/protect/internal modifiers
BindingFlag.Public -BindingFlags.Static -BindingFlags.Instance Specifies static and instance members decorated by public
BindingFlag.NonPublic – BindingFlags.Static – BindingFlags.Instance Specifies static and instance members decorated with private/ Protect /internal

Activator

The function of an Activator is to instantiate an object by reflecting several different constructs

  /// <summary>
    ///Instantiate objects by reflection
    /// </summary>
    private void NewObjByRef()
    {
        // Get the type
        Type heroType = typeof(Framework.Hero);

        // Create an instance of this class, constructed with public without a parameter
        // object heroObj = Activator.CreateInstance(heroType);
        // // converts to an object of the specified type
        // Framework.Hero hero = heroObj as Framework.Hero;

        // Create an instance of this class, constructed with a non-public, no-parameter construct
        Activator.CreateInstance(heroType, true);

        // Create an instance of this class, constructed with public parameters
        object daysHero = Activator.CreateInstance(heroType, 31);

        Debug.Log((daysHero as Framework.Hero).GetName()); 

        // Create an instance of this class, constructed with private parameters
        object privateHero = Activator.CreateInstance(heroType,
            BindingFlags.NonPublic | BindingFlags.Instance,
            null.new object[] { "QF" },
            null );
        
        Debug.Log((privateHero as Framework.Hero).attack);
    }
Copy the code

MemberInfo

MemberInfo is used to obtain the various members of a class through reflection

// Get the type
        Type heroType = typeof(Framework.Hero);
        // Get a member of a class
        // MemberInfo[] infos = heroType.GetMember("name");
        // Print the result
        // Debug.Log(infos[0].MemberType);

        Type goType = typeof(GameObject);
        
        // Get all non-public static members of a class
        MemberInfo[] memberInfos = goType.GetMembers(BindingFlags.NonPublic | BindingFlags.Static);

        for (int i = 0; i < memberInfos.Length; i++)
        {
            Debug.Log(memberInfos[i].Name + "|" + memberInfos[i].MemberType);
        }
Copy the code

FieldInfo

FieldInfo is used to retrieve the private member fields of an object through reflection

     #regionGets the private member field of an object through reflection
        // Declare an object of this class
        Framework.Hero akl = new Framework.Hero("Akari".123);
        Select * from 'name' where 'name' = 'name';
        FieldInfo fieldInfo = heroType.GetField("name",BindingFlags.NonPublic | BindingFlags.Instance);
        // Get the object, the value of this field
        string aklName = fieldInfo.GetValue(akl).ToString();
        // Set the object, the value of this field
        fieldInfo.SetValue(akl,"A thorn in the side.");
        Debug.Log("aklName:" + akl.GetName());
        #endregion

Copy the code

MethodInfo

MethodInfo is used to obtain the private method of a class by reflection

    #regionGets a private method of a class through reflection

        Framework.Hero ftml = new Framework.Hero(Clockwork spirits..80);
        
        // Get the non-static member method ShowMe
        MethodInfo info = heroType.GetMethod("ShowMe",
            BindingFlags.NonPublic |
            BindingFlags.Instance,null,CallingConventions.Any,new Type[] {typeof(string)}, null);

        // MethodInfo info = heroType.GetMethod("ShowMe",
        // BindingFlags.NonPublic |
        // BindingFlags.Instance,null,CallingConventions.Any,types, null);

        // Call the method
        info.Invoke(ftml, new object[] {"QF" });

        #endregion
Copy the code

The advantages and disadvantages

1. Reflection improves the flexibility and extensibility of the program. \color{FF66FF}{1, reflection improves the flexibility and extensibility of programs. }1. Reflection improves the flexibility and extensibility of programs. 2. Reduce the coupling and improve the adaptive ability. \color{FF66FF}{2, reduce the coupling, improve the adaptive ability. }2, reduce the coupling, improve the adaptive ability. 3. It allows programs to create and control objects of any class without having to hard-code the target class in advance. \color{FF66FF}{3. It allows programs to create and control objects of any class without having to hard-code the target class in advance. }3. It allows programs to create and control objects of any class without having to hard-code the target class beforehand.

Disadvantages 1. Performance issues: Using reflection is basically an interpreted operation, which is much slower than using direct code for field and method access. Therefore, the reflection mechanism is mainly applied to the system framework which requires high flexibility and extensibility, and is not recommended for ordinary programs. \color{2D4AFF}{1, Performance issues: Using reflection is basically an interpreted operation that is much slower for field and method access than for direct code. Therefore, the reflection mechanism is mainly applied to the system framework which requires high flexibility and extensibility, and is not recommended for ordinary programs. }1. Performance issues: Using reflection is basically an interpreted operation that is much slower for field and method access than for direct code. Therefore, the reflection mechanism is mainly applied to the system framework which requires high flexibility and extensibility, and is not recommended for ordinary programs. 2. Using reflection will obscure the internal logic of the program; The programmer wants to see the logic of the program in the source code, but reflection bypasses the technique of source code, thus causing maintenance problems. Reflected code is more complex than the corresponding direct code. \color{2D4AFF}{2, use reflection to blur the internal logic of the program; The programmer wants to see the logic of the program in the source code, but reflection bypasses the technique of source code, thus causing maintenance problems. Reflected code is more complex than the corresponding direct code. }2. Using reflection will obscure the internal logic of the program. The programmer wants to see the logic of the program in the source code, but reflection bypasses the technique of source code, thus causing maintenance problems. Reflected code is more complex than the corresponding direct code.

Tips reflection is very useful. This is just the definition of reflection and some ways to use it. If you want to do something more complex, you need to practice it in a project