C # reflection initial use, to achieve a class to find the same variable name character string and the string variable

C # using reflection achieved according to a string, a class to find variable names and the same variable character string, and assign it a value, this function may be used when responding to read table, and the like:

1, the inside of the character string type variables found

Find FieldTest class, the variable named name

 FieldTest fieldTest = new FieldTest();
System.Reflection.FieldInfo fieldInfo = fieldTest.GetType().GetField("name");

To name variable assignment:

 fieldInfo.SetValue(fieldTest, "亚里士多德");

2, the following is the complete code:

using UnityEngine;

public class Test : MonoBehaviour
{
    void Start()
    {
        FieldTest fieldTest = new FieldTest();

        System.Reflection.FieldInfo fieldInfo = fieldTest.GetType().GetField("name");
        fieldInfo.SetValue(fieldTest, "亚里士多德");

        fieldInfo = fieldTest.GetType().GetField("age");
        fieldInfo.SetValue(fieldTest, 123);

        print(string.Format("{0}的年龄有{1}岁了。", fieldTest.name, fieldTest.age));
    }    
}

public class FieldTest
{
    public string name;
    public int age;
}

Published 14 original articles · won praise 0 · Views 410

Guess you like

Origin blog.csdn.net/a0_67/article/details/105277106