C# 對象實例化 用json保管 泛型類 可以很方便的保管順序設置。本站提示廣大學習愛好者:(C# 對象實例化 用json保管 泛型類 可以很方便的保管順序設置)文章只能為提供參考,不一定能成為您想要的結果。以下是C# 對象實例化 用json保管 泛型類 可以很方便的保管順序設置正文
參考頁面:
http://www.yuanjiaocheng.net/webapi/test-webapi.html
http://www.yuanjiaocheng.net/webapi/web-api-controller.html
http://www.yuanjiaocheng.net/webapi/config-webapi.html
http://www.yuanjiaocheng.net/webapi/web-api-route.html
http://www.yuanjiaocheng.net/webapi/parameter-binding.html
用於永世化對象,什麼順序都行,依賴NewtonSoft。用於json序列化和反序列化。1 using Newtonsoft.Json; 2 using System; 3 using System.Collections.Generic; 4 using System.IO; 5 using System.Linq; 6 using System.Text; 7 using System.Threading.Tasks; 8 9 namespace ConfigHandler 10 { 11 public class ConfigHandler<T> 12 where T : class 13 { 14 const string SAVE_PATH = "jsonconfig/"; 15 /// <summary> 16 /// 單例形式 17 /// </summary> 18 static T config; 19 private ConfigHandler() 20 { 21 22 } 23 /// <summary> 24 /// 獲取保管地址,默許是泛型參數T的類型稱號 25 /// </summary> 26 /// <returns></returns> 27 private static string GetSavePath() 28 { 29 if (!Directory.Exists(SAVE_PATH)) 30 { 31 Directory.CreateDirectory(SAVE_PATH); 32 } 33 return $"{SAVE_PATH}{typeof(T).ToString()}.json"; 34 } 35 /// <summary> 36 /// 保管配置 37 /// </summary> 38 public static void Save(T _config) 39 { 40 config = _config; 41 string json = JsonConvert.SerializeObject(_config); 42 try 43 { 44 using (var sw = new StreamWriter(GetSavePath())) 45 { 46 sw.WriteAsync(json); 47 } 48 49 } 50 catch (Exception) 51 { 52 throw; 53 } 54 } 55 /// <summary> 56 /// 獲取配相信息 57 /// </summary> 58 /// <returns></returns> 59 public static T Load() 60 { 61 if (config == null) 62 { 63 string json = ""; 64 try 65 { 66 using (var sr = new StreamReader(GetSavePath())) 67 { 68 json = sr.ReadToEnd(); 69 if (json != "") 70 { 71 config = JsonConvert.DeserializeObject<T>(json); 72 } 73 else 74 { 75 config = null; 76 } 77 } 78 } 79 catch (Exception) 80 { 81 config = null; 82 } 83 } 84 return config; 85 } 86 87 } 88 89 90 }View Code
demo:
using ConfigHandler; using ConsoleApplication1; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { MyConfig config = new MyConfig(); config = new MyConfig(); config.name = "leiming"; config.Age = 20; config.Time = DateTime.Now; ConfigHandler<MyConfig>.Save(config); config = ConfigHandler<MyConfig>.Load(); Console.WriteLine(config.ToString()); Console.ReadKey(); } } class MyConfig { public int Hello{get;set;} public string name { get; set; } public int Age { get; set; } public DateTime Time { get; set; } public override string ToString() { return $"Name={name},Age={Age},Time={Time.ToShortDateString()}"; } } }View Code