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