C# 类型转换
/// <summary> /// 将DataTable 转换为 List集合 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="dt"></param> /// <returns></returns> public List<T> DtToModel<T>(DataTable dt) where T : class, new() { List<T> list = new List<T>(); T model = new T(); Type type = typeof(T); PropertyInfo[] props = type.GetProperties(); foreach (DataRow dr in dt.Rows) { foreach (var item in props) { if (dt.Columns.Contains(item.Name)) { item.SetValue(model, dr[item.Name]); } } list.Add(model); } return list; }
/// <summary> /// 将实体模型转换为DataTable /// </summary> /// <typeparam name="T"></typeparam> /// <param name="model"></param> /// <returns></returns> public DataTable ModelToDt<T>(T model) where T : class, new() { Type type = typeof(T); DataTable dt = new DataTable(); PropertyInfo[] props = type.GetProperties(); foreach (var item in props) { dt.Columns.Add(item.Name); } DataRow dr = dt.NewRow(); foreach (var item in props) { if (dt.Columns.Contains(item.Name)) { dr[item.Name] = item.GetValue(model); } } dt.Rows.Add(dr); return dt; }