反射修改属性字段内容(动态转换 DataRowToModel)

本文介绍了一种将DataRow转换为指定类型对象模型的方法,通过反射机制遍历DataRow的每一列,并将其值转换为对象属性的对应类型,适用于.NET平台的数据处理场景。

仅作学习笔记记录使用,大牛绕行

 

        public T DataRowToModel<T>(DataRow row) where T : class, new()
        {

            T model = new T();

            if (row != null)
            {
                foreach (DataColumn item in row.Table.Columns)
                {
                    if (row[item.ColumnName] != null && row[item.ColumnName].ToString() != "")
                    {
                        Type type = typeof(T);
                        var list = type.GetProperties(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.IgnoreCase);
                        string value = row[item.ColumnName].ToString();
                        foreach (var property in list)
                        {
                            if (!property.PropertyType.IsGenericType)
                            {
                                //非泛型
                                property.SetValue(model, string.IsNullOrEmpty(value) ?
                                null : Convert.ChangeType(value, property.PropertyType), null);

                            }
                            else
                            {
                                //泛型Nullable<>
                                Type genericTypeDefinition = property.PropertyType.GetGenericTypeDefinition();
                                if (genericTypeDefinition == typeof(Nullable<>))
                                {
                                    property.SetValue(model, string.IsNullOrEmpty(value) ? null : Convert.ChangeType(value, Nullable.GetUnderlyingType(property.PropertyType)), null);
                                }
                            }
                            break;
                        }
                    }
                }
                return model;
            }
            else
            {
                return null;
            }
        }

  

转载于:https://www.cnblogs.com/ugvnui/p/9719821.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值