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;
        }

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

 

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

 

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

 

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM