Home>

Is it possible to obtain and output the fields of a class at once?
Please teach me.

Applicable source code

Process that is obtained and output for each field in Debug.Log as shown below
Isn't it possible to process all m fields in a batch, and output the field name and its value by foreach?

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Model {
    public int mId = 0;
    public string mName = "";
    public string mPath = "";
    public int mType = 0;
    private int i = 10;
}
public class Sample: MonoBehaviour {
    void Start () {
        Model m = new Model ();
        m.mId = 1;
        m.mName = "name";
        m.mPath = "root";
        m.mType = 2;
        Debug.Log ("mId" + m.mId);
        Debug.Log ("mName" + m.mName);
        Debug.Log ("mPath" + m.mPath);
        Debug.Log ("mType" + m.mType);
        // The above process of Debug.Log is obtained in a batch of m fields,
        // Can't you output by turning with a foreach statement?
        foreach () {
        }
    }
}
Append
// Private fields are not included.
        FieldInfo [] infoArray = m.GetType (). GetFields ();
        foreach (FieldInfo info in infoArray)
        {
            Debug.Log (info.Name + ":" + info.GetValue (m));
        }
        // Get only private fields.
        FieldInfo [] infoArray2 = m.GetType (). GetFields (BindingFlags.Instance | BindingFlags.NonPublic);
        foreach (FieldInfo info in infoArray2)
        {
            Debug.Log (info.Name + ":" + info.GetValue (m));
        }