C# 获取类中所有的属性

通常用到的方法是通过反射进行获取:

例如有如下Student类:

    public class Student
    {
        private string id;
        public string Id { get { return id; } set { id = value; } }

        private string name;
        public string Name { get { return name; } set { name = value; } }

        private string age;
        public string Age { get { return age; } set { age = value; } }
    }

需要添加的命名空间:

    using System.Reflection;

具体的反射方法如下所示:

        private PropertyInfo[] GetPropertyInfoArray()
        {
            PropertyInfo[] props = null;
            try
            {
                Type type = typeof(EricSunApp.Student);
                object obj = Activator.CreateInstance(type);
                props = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
            }
            catch (Exception ex)
            { }
            return props;
        }

之后就是对返回来的数组进行遍历了。

获取一个类中所有的字段也是类似的方法:

可以再上网查一下关于反射的更多知识。。。。

原文地址:https://www.cnblogs.com/mingmingruyuedlut/p/2849903.html