DataTable或者DataRow转换对象
public static IEnumerable<T> ConvertObject<T>(DataTable dt) where T : new() { var v = typeof(T).GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance); List<PropertyInfo> Fields = new List<PropertyInfo>(); foreach (var s in v) { if (dt.Columns.Contains(s.Name)) Fields.Add(s); } foreach (DataRow dr in dt.Rows) { T t = new T(); foreach (var s in Fields) { if (object.Equals(dr[s.Name], DBNull.Value)) continue; s.SetValue(t, dr[s.Name], null); } yield return t; } } public static T ConvertObject<T>(DataRow dr) where T : new() { var v = typeof(T).GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance); T t = new T(); foreach (var s in v) { if (dr.Table.Columns.Contains(s.Name)) { s.SetValue(t, dr[s.Name], null); } } return t; }
Bug,
1.如果泛型对象(T)属性的类型和DataTable列的类型不一致,抛异常 ---懒得解决
2.DBNull.value转换失败,新方法
public static T ConvertObject<T>(DataRow dr) where T : new() { var v = typeof(T).GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance); T t = new T(); foreach (var s in v) { if (dr.Table.Columns.Contains(s.Name)) { if (object.Equals(dr[s.Name], DBNull.Value)) continue; { s.SetValue(t, dr[s.Name]); } } } return t; }
慎于行,敏于思!GGGGGG