通过反射将实体中的属性和值转换为字典项

        /// <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;
        }
博客内容主要用于日常学习记录,内容比较随意,如有问题,还需谅解!!!
原文地址:https://www.cnblogs.com/YYkun/p/15233926.html