public static T ConvertToModel<T>(DataRow dr) where T : new() { T t = new T(); Type modelType = t.GetType(); foreach (PropertyInfo pi in modelType.GetProperties()) { if (pi == null) continue; if (pi.CanWrite == false) continue; if (dr.Table.Columns.Contains(pi.Name)) { //p.SetValue(t, GetDefaultValue(dr[p.Name], p.PropertyType), null); try { if (dr[pi.Name] != DBNull.Value) pi.SetValue(t, dr[pi.Name], null); else pi.SetValue(t, default(object), null); } catch { pi.SetValue(t, GetDefaultValue(dr[pi.Name], pi.PropertyType), null); } } } return t; } private static object GetDefaultValue(object obj, Type type) { if (obj == DBNull.Value) { return default(object); } else { return Convert.ChangeType(obj, type); } }
纯代码难得打字
时间: 2024-10-10 06:23:30