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.附:源码

  • 相关阅读:
    C++primer拾遗(第五章:语句)
    每日编程-20170315
    C++primer拾遗(第四章:表达式)
    C++primer拾遗(第三章:字符串、向量和数组)
    每日编程-20170314
    C++primer拾遗(第二章:变量和基本类型)
    每日编程-20170313
    每日编程-20170310
    每日编程-20170309
    C++primer拾遗(第一章:开始)
  • 原文地址:https://www.cnblogs.com/vakeynb/p/8116839.html
Copyright © 2011-2022 走看看