- 新增实体属性方法:
/// <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.附:源码