C#反射获取类的成员变量名称及值

//测试用的类
public class PersonData
{
    public string gender = string.Empty;
    public List<int> pifuRGB = new List<int>() { 0, 0, 0 };
    public int meiGray;
    string testStr = string.Empty;
}
void Fun(){
    PersonData p = new PersonData();
    //获取p对象中的public成员变量
    //GetType().GetProperties()是获取公开属性
    foreach(System.Reflection.FieldInfo item in p.GetType().GetFields())
    {
        if (item.FieldType.Equals(typeof(string)) || item.FieldType.Equals(typeof(int)) || item.FieldType.Equals(typeof(float)))
        {
            print(item.Name + " " + item.GetValue(p));
        }
        //泛型类型的处理
        else if (item.FieldType.Equals(typeof(List<int>)))
        {
            object subObj = item.GetValue(p);
            if (subObj != null)
            {
                int count = Convert.ToInt32(subObj.GetType().GetProperty("Count").GetValue(subObj, null));
                    for (int i = 0; i < count; i++)
                    {
                        //获取列表子元素,若子元素是类,则再进行反射获取
                        object sub = subObj.GetType().GetProperty("Item").GetValue(subObj, new object[] { i });
                        int value = Convert.ToInt32(sub);
                        print(item.Name + " " + i + " " + value.ToString());
                    }
            }
        }
    }
}
posted @ 2021-09-01 08:59  蓝闪  阅读(1862)  评论(0编辑  收藏  举报