Using reflection in C# to convert a string to a class

In the process of using unity as a demo, I want to load the prefab of the UI interface into the scene from the configuration table and mount the corresponding classes. Since the classes that need to be mounted in the configuration table are configured through strings, So I thought of adding it in the form of reflection, and made the following attempts:

public class TestReflection : MonoBehaviour
{    
    // Start is called before the first frame update
    void Start()
    {
        string className = "Person";
        Type t = Type.GetType(className);

        //创建实例对象
        var obj = t.Assembly.CreateInstance(className);

        MethodInfo method = t.GetMethod("SetPersonName");
        method.Invoke(obj,new object[] { "Danny"});
    } 
}
public class Person
{
    public void SetPersonName(string name)
    {
        Debug.Log("personName:" + name);
    }
}

In the above code, Type.GetTyoe() is used to convert the string into a class through reflection, and the method in the class can be obtained through the GetMethod function.

In order to mount the reflected class on the object, the code is modified as follows:

using UnityEngine;
using System.Reflection;
using System;
public class TestReflection : MonoBehaviour
{    
    void Start()
    {
        string className = "Person";
        Type t = Type.GetType(className);

        //创建实例对象
        var obj = t.Assembly.CreateInstance(className);

        MethodInfo method = t.GetMethod("SetPersonName");
        method.Invoke(obj,new object[] { "Danny"});

        //将函数挂载到物体上
        GameObject go = GameObject.CreatePrimitive(PrimitiveType.Cube);
        go.AddComponent(t);
        //注意此处无法使用泛型参数挂载函数  go.AddComponent<t>();
    }
}
public class Person:MonoBehaviour
{
    public void SetPersonName(string name)
    {
        Debug.Log("personName:" + name);
    }
}

 

Guess you like

Origin blog.csdn.net/l17768346260/article/details/104139577