2.調用: 3.結果: 4.附:Json方法 5.附:源碼——https://files.cnblogs.com/files/vakeynb/%E4%B8%BA%E5%AE%9E%E4%BD%93%E6%96%B0%E5%A2%9E%E5%B1%9E%E6%80%A7.7z ...
- 新增實體屬性方法:
/// <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.附:源碼——https://files.cnblogs.com/files/vakeynb/%E4%B8%BA%E5%AE%9E%E4%BD%93%E6%96%B0%E5%A2%9E%E5%B1%9E%E6%80%A7.7z