zoukankan      html  css  js  c++  java
  • 实体新增属性

    1. 新增实体属性方法:
            /// <summary>
            /// 为实体新增属性,返回字典
            /// </summary>
            /// <param name="propertyName">新增属性名称</param>
            /// <param name="propertyValue">新增属性值</param>
            /// <param name="entity">实体</param>
            /// <param name="outDic">要返回的字典</param>
            public static void AddProperty(string propertyName, object propertyValue, object entity, out Dictionary<string, object> outDic)
            {
                Dictionary<string, object> dt = new Dictionary<string, object>();
    
                Type t = entity.GetType();
                for (int i = 0; i < t.GetProperties().Length; i++)
                {
                    dt.Add(t.GetProperties()[i].Name, t.GetProperties()[i].GetValue(entity));
                }
    
                if (dt.ContainsKey(propertyName) == false)
                {
                    dt.Add(propertyName, propertyValue);
                }
                else
                {
                    dt[propertyName] = propertyValue;
                }
                outDic = dt;
    
            }

      2.调用:

               //StudentEntity student = new StudentEntity() { StuNo = "001", Name = "张三" ,Age=18};
                var student = new { StuNo = "001", Name = "张三", Age = 18 };
                Dictionary<string, object> dt = new Dictionary<string, object>();
                AddProperty("Hobby", "羽毛球", student, out dt);//新增属性
    
                Console.WriteLine(dt.ToJson());
                Console.ReadLine();

      3.结果:

      

      4.附:Json方法

      //一定要引用dll:  Newtonsoft.Json
      public static class Json
        {
            public static string ToJson(this object obj)
            {
                var timeConverter = new IsoDateTimeConverter { DateTimeFormat = "yyyy-MM-dd HH:mm:ss" };
                return JsonConvert.SerializeObject(obj, timeConverter);
            }
        }

       5.附:源码

  • 相关阅读:
    页面滚动性能优化之passive
    【webpack4x】部分底层原理及手写一个简单打包工具
    【webpack4x】实战配置及问题解析
    【webpack4x】高级概念
    【webpack4x】核心概念
    VMware虚拟机服务的vmware-hostd自动启动和停止
    海淘电商网址
    一键批量ping任意ip段的存活主机
    cpanel导入大数据库(mysql)的方法
    awstats 日志分析
  • 原文地址:https://www.cnblogs.com/vakeynb/p/8116839.html
Copyright © 2011-2022 走看看