使用反射遍历类的属性

来源:互联网 发布:htc windows系统手机 编辑:程序博客网 时间:2024/06/08 20:03

这个方法还是很简单的,通过反射即可遍历属性,我总结的方法如下:

class ForeachClass    {          /// <summary>        /// C#反射遍历对象属性        /// </summary>        /// <typeparam name="T">对象类型</typeparam>        /// <param name="model">对象</param>        public static void ForeachClassProperties<T>(T model)        {            Type t = model.GetType();            PropertyInfo[] PropertyList = t.GetProperties();            foreach (PropertyInfo item in PropertyList)            {                string name = item.Name;                object value = item.GetValue(model, null);                Console.WriteLine("name:" + name + " " + "value:" + value);            }        }    }


   下面我们来简单测试下:

    新建Model如下:

    class AddressInfo    {        public int Id { get; set; }        public string userName { get; set; }        public string userTel { get; set; }        public string Addressdetail { get; set; }        public int isMoren { get; set; }        public AddressInfo()        {            Id = 1;            userName = "张三";            userTel = "1813707015*";            Addressdetail = "北京天安门";            isMoren = 1;        }    }


   调用如下:

 static void Main(string[] args)        {            //Response.Redirect("/Home/Login");            AddressInfo model = new AddressInfo();            ForeachClass.ForeachClassProperties<AddressInfo>(model);            Console.ReadKey();        }

   测试结果如下:


   经过测试,我们可以得到对象的各个属性及对应的值、

阅读全文
0 0