[Unity3D daily development] The use of C# reflection in Unity3D

Recommended reading

Hello everyone, I'm a Buddhist engineer ☆Quiet little magic dragon☆ . I update Unity development skills from time to time. If you find it useful, remember to click three times.

Your likes are your support for bloggers. If you have any questions, remember to leave a message:
insert image description here

I. Introduction

Today, I will share a concept that I rarely come into contact with in my daily development—reflection. I recently used it when writing code, so I share it. On the one hand, it is a summary of the knowledge I have learned, and on the other hand, it is also to help later people. .

Although reflection is not used much, there is a reason for it, and the application scenarios of reflection will be discussed in the following sections.

Second, C# reflection (Relection) learning

2-1. What is reflection

Reflection, English name Selection, is a way to obtain runtime type information in .Net. A .Net application consists of three parts:

  • Assembly (Assembly)
  • Module
  • Type (Class)

Reflection provides some excuses so that the program can obtain the information of these components when the program is running, for example:

  • Get the running assembly and create an instance of the type based on the type information in the assembly.
  • Get the type information of the object, such as methods, constructors, properties, etc.
  • Get the method name, parameters, return value, etc. of the class.

To sum up, it is: a mechanism for a program to access, detect and modify its own state, dynamically create an instance and execute the methods in it.

2-2. Application scenarios of reflection

Having said so much, reflection seems to be very useful, but it seems to be very useless. Where is it used?

Reflection is mainly useful in the following situations:

  • View feature information at runtime and access properties in program metadata.
  • Look at the types in the collection at runtime, and instantiate those types.
  • Build new types at runtime, and use these types to perform some tasks.
  • Bind and access methods of the created type at runtime.

For a simple example, we have a program play.exethat uses say.dlland walk.dll, and suddenly the customer says to add a running function, then we only need to make one according to our agreed rules run.dll, and the previous one play.execan be used directly without any modification. run.dll, you don't need to open the editor, run.dllimport it, and generate it play.exe.


For more functions, see the following table (this table is quoted from https://blog.csdn.net/q493201681/article/details/82623802 ):

Types of effect
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 (like public or private), and implementation details (like abstract or virtual), etc. Use Type's GetConstructors or GetConstructor methods to call a specific constructor.
MethodInfo Know the method's name, return type, parameters, access modifiers (like public or private) and implementation details (like abstract or virtual), etc. Use the type's GetMethods or GetMethod method to call a specific method.
FieldInfo Know the name of the field, method modifiers (like public or private) and implementation details (like static), etc., and get or set the field value.
EventInfo Know the name of the event, event handler data type, custom attributes, declared or reflected type, etc., and add or remove event handlers.
PropertyInfo Know the property's name, data type, declared type, reflection type, read-only or writable status, 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, etc., and the location of the parameter in the method signature, etc.

2-3. What is the use of getting type information at runtime

Having said so much, some people may say, what is the use of getting type information at runtime, I can write good code during development, why do it in reflection, it is not only troublesome, but also inefficient.

This is a problem where the benevolent sees benevolence and the wise sees wisdom. Just like early binding and late binding, there are different application scenarios.

Existence is reasonable, and proper use can greatly improve the reusability and flexibility of programs, but there are advantages and disadvantages.

2-4, the advantages and disadvantages of reflection

advantage:

  • Increased program flexibility and extensibility
  • Reduce coupling and improve program adaptability
  • Allows creation and control of class objects at runtime, out-of-order hard-coding target classes ahead of time

shortcoming:

  • Reflection is an interpretation operation, which is slower than direct code when used. It is recommended to be used in projects that require high flexibility and scalability.
  • Reflection complicates the code. Reflection bypasses the technology of source code, which brings some problems for maintenance, which is more complicated than direct code.

2-5. Application examples of reflection

1、获取程序集信息和类型信息

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Reflection;
using System;

public class ReflectionGetInfo : MonoBehaviour
{
    
    
    public string Name;
    public int Age;
    public bool Sex;

    public void Fun1(){
    
    }
    public void Fun2(){
    
    }

    void Start()
    {
    
    
        //获取类型
        Type t = GetType();
        Debug.Log(t.Name);//类名
        Debug.Log(t.Namespace);//所属命名空间
        Debug.Log(t.Assembly.ToString());//程序集信息
        FieldInfo[] fi = t.GetFields();//获取类中的字段
        foreach (var f in fi)
            Debug.Log(f.Name);
        MethodInfo[] mh = t.GetMethods();//获取所有的方法
        foreach (var h in mh)
            Debug.Log(h.Name);
    }
}

operation result:
insert image description here
2、动态创建类型实例并执行其中的方法

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using System.Reflection;

public class CreateReflectionDemo : MonoBehaviour
{
    
    
    void Start()
    {
    
    
        //动态创建类,并执行方法
        CreateReflectionClass(1);
    }

    private void CreateReflectionClass(int index)
    {
    
    
        string AssemblyName = Assembly.GetExecutingAssembly().GetName().Name;//获取程序集名称
        string strNameSpace = MethodBase.GetCurrentMethod().DeclaringType.Namespace;//获取命名空间名称;
        string strClassName = "Fun" + index;//获取类型名
        string fullclassName = strNameSpace + "." + strClassName;//类全名(命名空间.类名称)
        MyClass mys = (MyClass)Assembly.Load(AssemblyName).CreateInstance(fullclassName);
        mys.GetResult();
    }
}
public interface MyClass
{
    
    
    void GetResult();
}
public class Fun1 : MyClass
{
    
    
    public void GetResult()
    {
    
    
        Debug.Log("I'm Fun1");
    }
}
public class Fun2 : MyClass
{
    
    
    public void GetResult()
    {
    
    
        Debug.Log("I'm Fun2");
    }
}

operation result:
insert image description here

3. Postscript

Today I share what reflection is and how to use it.

Reflection is primarily a way to obtain type information at runtime, but also to dynamically create instances and execute methods within them.

Then a simple example is used to demonstrate how to use reflection, but there are still many uses of reflection, which need readers to explore by themselves.


The blogger also has many treasure articles waiting for you to discover:

column direction Introduction
Unity3D develops small games Small game development tutorial Share some small games developed using the Unity3D engine, and share some tutorials for making small games.
Unity3D from entry to advanced getting Started Get inspiration from self-study Unity, summarize the route of learning Unity from scratch, with knowledge of C# and Unity.
Unity 3D yuki UGUI UGUI Unity's UI system UGUI is fully analyzed, starting from the basic controls of UGUI, and then comprehensively teaching the principles of UGUI and the use of UGUI.
Unity3D read data file read Use Unity3D to read txt documents, json documents, xml documents, csv documents, and Excel documents.
Unity3D data collection Data collection Array collection: Knowledge sharing of data collections such as arrays, Lists, dictionaries, stacks, linked lists, etc.
VR/AR (Virtual Simulation) Development of Unity3D virtual reality Summarize the common virtual simulation requirements of bloggers' work for case explanation.
Plugin for Unity3D plugin Mainly share some plug-in usage methods used in Unity development, plug-in introduction, etc.
Daily development of Unity3D daily record Mainly used by bloggers in daily development, methods and skills used, development ideas, code sharing, etc.
Daily BUG of Unity3D daily record Record the bugs and pits encountered in the process of developing projects with the Unity3D editor, so that later people can refer to them.

Guess you like

Origin blog.csdn.net/q764424567/article/details/123503141