1.公共方法
1 #region dataConvert 2 /// <summary> 3 /// 从数据行返回数据实体对象 4 /// </summary> 5 /// <typeparam name="T">数据实体类型</typeparam> 6 /// <param name="row">数据行</param> 7 /// <returns>数据实体对象</returns> 8 public static T GetModel<T>(DataRow row) where T : class, new() 9 { 10 if (row == null) return null; 11 12 T result = new T(); 13 14 Type type = typeof(T); 15 16 System.Reflection.PropertyInfo[] ps = type.GetProperties(); 17 18 foreach (System.Reflection.PropertyInfo p in ps) 19 { 20 if (row.Table.Columns.Contains(p.Name)) 21 { 22 object value = row[p.Name]; 23 24 if (!(value is DBNull)) 25 { 26 try 27 { 28 p.SetValue(result, value, null); 29 } 30 catch 31 { 32 33 } 34 } 35 } 36 } 37 38 return result; 39 } 40 /// <summary> 41 /// 从数据表返回数据实体列表对象 42 /// </summary> 43 /// <typeparam name="T">数据实体类型</typeparam> 44 /// <param name="dt">数据表</param> 45 /// <returns>数据实体列表对象</returns> 46 public static List<T> GetModelList<T>(DataTable dt) where T : class, new() 47 { 48 List<T> list = new List<T>(); 49 foreach (DataRow row in dt.Rows) 50 { 51 list.Add(GetModel<T>(row)); 52 } 53 return list; 54 } 55 56 /// <summary> 57 /// 从数据行集合返回数据实体列表对象 58 /// </summary> 59 /// <typeparam name="T">数据实体类型</typeparam> 60 /// <param name="rows">数据行集合</param> 61 /// <returns>数据实体列表对象</returns> 62 public static List<T> GetModelList<T>(IEnumerable<DataRow> rows) where T : class, new() 63 { 64 List<T> list = new List<T>(); 65 foreach (DataRow row in rows) 66 { 67 list.Add(GetModel<T>(row)); 68 } 69 return list; 70 } 71 #endregion
2.调用
1 SYSUser sysUser = Session["SYSUser"] as SYSUser; 2 DataSet ds = T_SYS_ManageUsersBll.Instance.GetSysMenu(sysUser.LoginName); 3 List<T_TMP_SysMenu> menulist1 = DataUtil.GetModelList<T_TMP_SysMenu>(ds.Tables[0]);