首页 > 其他 > 详细

一种反射的方式

时间:2014-04-10 19:17:13      阅读:457      评论:0      收藏:0      [点我收藏+]
bubuko.com,布布扣
/// <summary>转记录表到模型列表</summary>
        /// <typeparam name="T">模型类型</typeparam>
        /// <param name="table">记录表</param>
        /// <returns>模型列表</returns>
        public static List<T> ConvertToModelList<T>(DataTable table)
        {
            List<T> result = new List<T>();
            if (null == table || 0 == table.Rows.Count) { return result; }

            foreach (DataRow dr in table.Rows)
            {
                T model = Activator.CreateInstance<T>();
                // 如果失败就用这个方式:Activator.CreateInstance(assemblyName, typeName);
                Type type = model.GetType();
                foreach (PropertyInfo property in type.GetProperties())
                {
                    string propertyName = property.Name;

                    //property.SetValue(model, dr[propertyName], null);

                    //try { property.SetValue(model, Convert.ChangeType(dr[propertyName], property.PropertyType), null); } catch { }

                    property.SetValue(model, Convert.ChangeType(dr[propertyName], property.PropertyType), null);
                }
                result.Add(model);
            }
            return result;
        }
bubuko.com,布布扣

 

一种反射的方式,布布扣,bubuko.com

一种反射的方式

原文:http://www.cnblogs.com/caoyinglai/p/3655680.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!