一种反射的方式

/// <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;
        }
原文地址:https://www.cnblogs.com/caoyinglai/p/3655680.html