且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

.net中通过反射得到所有的私有字段(包括父类)

更新时间:2022-08-16 11:59:06

在.net中,利用反射可以很容易获取类的字段,属性和方法,不管是私有的,公有的还是受保护的,但如果一个类继承了其它的类,想要获取全部的属性或字段或方法似乎没有直接的方法。通过参考Java并实际实践,找到一个折中的办法。Demo如下:
首先定义两个类(Student继承自People)

点击(此处)折叠或打开

public class People
    {
        private string _Name;
        private string _Sex;
        private string _Age;

        public string Name
        {
            get { return this._Name; }
            set { this._Name = value; }
        }

        public string Sex
        {
            get { return this._Sex; }
            set { this._Sex = value; }
        }

        public string Age
        {
            get { return this._Age; }
            set { this._Age = value; }
        }
    }

    public class Student : People
    {
        private string _StuNo;
        private string _SchoolName;
        public string StuNo { get { return this._StuNo; } set { this._StuNo = value; } }

        public string SchoolName
        {
            get { return this._SchoolName; }
            set { this._SchoolName = value; }
        }
    }

通过反射取所有的私有字段

点击(此处)折叠或打开

List<FieldInfo> fieldList = new List<FieldInfo>();
            People stu = new Student();
            Type type = stu.GetType();
            FieldInfo[] fieldInfos = type.GetFields(BindingFlags.NonPublic | BindingFlags.Instance );
            fieldList.AddRange(fieldInfos);
            while((type = type.BaseType) != typeof(object))
            {
                fieldList.AddRange(type.GetFields(BindingFlags.NonPublic | BindingFlags.Instance));
            }

折中的地方是通过类的类型包含的BaseType属性找到父类型,当父类型不是object时一直取所有的私有字段并添加到List中即可。
​权当记录,以备后查。