反射-类属性

1.定义model

 class UserModel
    {
        /// <summary>
        /// 元素特性  可以指定多个 如:[Column(Name ="username", DbType = "int")]
        /// </summary>
        [Column(Name ="username")]
        public string name { get; set; }
        [Column(Name = "userpwd")]
        public string pwd { get; set; }
    }

2.引入命名空间

using System.Data.Linq.Mapping;
using System.Reflection;

3.创建测试数据

//创建测试数据
            DataTable dt = new DataTable();
            dt.Columns.Add("username", typeof(string));
            dt.Columns.Add("userpwd", typeof(string));
            DataRow dr = dt.NewRow();
            dr["username"] = "zhangsan";
            dr["userpwd"] = "123";
            dt.Rows.Add(dr);
            // 测试数据创建结束
            UserModel user = new UserModel();
            //通过反射 获取UserModel类的所有属性集合
            PropertyInfo[] properties = user.GetType().GetProperties();
            // 遍历 属性集合
            foreach (PropertyInfo f in properties)
            {
                // 获取属性的 特性
                object[] o = f.GetCustomAttributes(typeof(System.Data.Linq.Mapping.ColumnAttribute), false);
                if (o.Length == 0) continue;
                ColumnAttribute[] columns = o as System.Data.Linq.Mapping.ColumnAttribute[];
                if (columns.Length == 0) continue;
              
                // 检测表中是否存在列
                if (!dt.Columns.Contains(columns[0].Name)) continue;
                // 获取特性 Name 值
               // this.textEdit1.Text += columns[0].Name;
               
                // 判断属性的类型 - 赋值
                if (dt.Rows[0][columns[0].Name] == DBNull.Value)
                {
                    if (f.PropertyType == typeof(int))
                    {
                        f.SetValue(user, 0, null);
                    }
                    if(f.PropertyType == typeof(string))
                    {
                        f.SetValue(user, "", null);
                    }
                    if (f.PropertyType == typeof(DateTime))
                    {
                        f.SetValue(user, null, null);
                    }
                }
                else
                {
                    // 设置 对象属性 的值
                    f.SetValue(user, dt.Rows[0][columns[0].Name], null);
                }
            }

 

注:

可以新建类 集成自 ColumnAttribute , 添加自定义特性元素, 继承自 Attribute

  [AttributeUsage(AttributeTargets.Property,AllowMultiple =true,Inherited =false)]
    public class ColumnAttributeExt : Attribute
    {
        public string Fied { get; set; }
    }

使用:

[ColumnAttributeExt(Fied ="name")]
   public string ss { get; set; }

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值