C#的字典是否可以形成一个单独的文件?
写程序的时候,需要建立字典,但是字典里内容太多,写在类里看着很乱。能否让字典独立成某种文件,这样也方便修改。并且,如何引用这个独立出来的文件?
using System; using System.Collections.Generic; using using System.Data; using System.Drawing; using using System.Linq; using System.Runtime.Serialization; using System.Runtime.Serialization.Json; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Direct { public partial class Form1 : Form { [DataContract] public class MyClass { [DataMember] public Dictionary<int, string> myDictionary = new Dictionary<int, string>(); } MyClass myClass = new MyClass(); public Form1() { InitializeComponent(); myClass.myDictionary.Add(1, "C#"); myClass.myDictionary.Add(2, "C++"); myClass.myDictionary.Add(3, ""); myClass.myDictionary.Add(4, "MVC"); } private void button1_Click(object sender, EventArgs e) { ObjectToJson(myClass, "123.json"); } private void button2_Click(object sender, EventArgs e) { myClass.myDictionary.Clear(); myClass =JsonFileToObject<MyClass>("123.json"); } /// 将对象序列化为json文件 public static void ObjectToJson<T>(T t, string path) where T : class { DataContractJsonSerializer formatter = new DataContractJsonSerializer(typeof(T)); using (FileStream stream = new FileStream(path, FileMode.Create)) { formatter.WriteObject(stream, t); } } /// json字符串转成对象 public static T JsonToObject<T>(string json) where T : class { DataContractJsonSerializer formatter = new DataContractJsonSerializer(typeof(T)); using (MemoryStream stream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(json))) { T result = formatter.ReadObject(stream) as T; return result; } } /// json文件转成对象 public static T JsonFileToObject<T>(string path) where T : class { string str = File.ReadAllText(path, Encoding.UTF8); return JsonToObject<T>(str); } } }
[此贴子已经被作者于2022-8-15 20:13编辑过]