首页 > 其他 > 详细

利用泛型和反射实现IDataReader转实体

时间:2018-02-23 11:22:21      阅读:171      评论:0      收藏:0      [点我收藏+]
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);
        }

 

利用泛型和反射实现IDataReader转实体

原文:https://www.cnblogs.com/highest/p/8461175.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!