public static T ReaderToModel<T>(IDataReader row) { // 1、使用与指定参数匹配最高的构造函数,来创建指定类型的实例 Type modelType = typeof(HShopingCarModel); T model = Activator.CreateInstance<T>(); for (int i = 0; i < row.FieldCount; i++) { // 2、判断字段值是否为空或不存在的值 if (!(row[i] == null || row[i] is DBNull)) { // 3、匹配字段名 PropertyInfo pi = modelType.GetProperty(row.GetName(i), BindingFlags.GetProperty | BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase); if (pi != null) { // 4、绑定实体对象中同名的字段 pi.SetValue(model, CheckType(row[i], pi.PropertyType), null); } } } return model; } /// <summary> /// 对可空类型进行判断转换(*要不然会报错) /// </summary> /// <param name="value">DataReader字段的值</param> /// <param name="conversionType">该字段的类型</param> /// <returns></returns> private static object CheckType(object value, Type conversionType) { if (conversionType.IsGenericType && conversionType.GetGenericTypeDefinition().Equals(typeof(Nullable<>))) { if (value == null) return null; System.ComponentModel.NullableConverter nullableConverter = new System.ComponentModel.NullableConverter(conversionType); conversionType = nullableConverter.UnderlyingType; } return Convert.ChangeType(value, conversionType); }