zoukankan      html  css  js  c++  java
  • 通过反射将实体中的属性和值转换为字典项

            /// <summary>
            /// 实体转字典项
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <returns></returns>
            public Dictionary<string, string> EntityToDictionary<ThunisRecordDataClouumns>(ThunisRecordDataClouumns thunisRecordDataClouumns)
            {
                //初始化定义一个键值对,注意最后的括号
                Dictionary<string,string> dic = new Dictionary<string, string>();
                //返回当前Type 的所有公共属性Property集合
                PropertyInfo[] props = typeof(ThunisRecordDataClouumns).GetProperties();
                foreach (PropertyInfo p in props) {        
                    var value=p.GetValue(thunisRecordDataClouumns); //获取属性值
    
                    var property = thunisRecordDataClouumns.GetType().GetProperty(p.Name); //获取property对象
                    object[] objs = property.GetCustomAttributes(typeof(DescriptionAttribute), true); //获取属性注释
                    dic.Add(((DescriptionAttribute)objs[0]).Description, value.ToString());  //key是属性注释,value是属性值
                    //dic.Add(p.Name, value.ToString());   //key是属性名,value是属性值
                }
                return dic;
            }
            /// <summary>
            /// 将转换出来的属性添加到list中
            /// </summary>
            /// <param name="thunisRecordDataClouumns">实体对象</param>
            /// <returns></returns>
            public List<ContractEntry> Test(ThunisRecordDataClouumns thunisRecordDataClouumns)
            {
                Dictionary<string, string> dic = this.EntityToDictionary(thunisRecordDataClouumns);
    
                List<ContractEntry> listContractEntry = new List<ContractEntry>();
                ContractEntry contractEntry = new ContractEntry();           
                foreach (KeyValuePair<string, string> item in dic)
                {
                    contractEntry.FieldName = item.Key;
                    contractEntry.FieldValue = item.Value;
                    listContractEntry.Add(contractEntry);
                }
                return listContractEntry;
            }
    博客内容主要用于日常学习记录,内容比较随意,如有问题,还需谅解!!!
  • 相关阅读:
    JS-记住用户名【cookie封装引申】
    JS-cookie封装
    JS-比较函数中嵌套函数,可以排序【对象数组】
    JS-随机div颜色
    JS-过滤敏感词【RegExp】
    JS-提取字符串—>>普通方法VS正则表达式
    CSS- ie6,ie7,ie8 兼容性写法,CSS hack写法
    JS-【同页面多次调用】轮播特效封装-json传多个参数
    JS-【同页面多次调用】tab选项卡封装
    Redis主从同步
  • 原文地址:https://www.cnblogs.com/YYkun/p/15233926.html
Copyright © 2011-2022 走看看