C# 对象持久化

对象持久化是指将内存中的对象保存到可永久保存的存储设备中(如磁盘)的一种技术。

本文介绍的是除数据库之外的二种对象持久化模式。

切实如下:

  1. 封存成文本:即将内存对象以字节流的主意保留到文本中。
  2. 队列化成Xml:即将对象以Xml的格式存储。
  3. 体系化成Json:即将对象连串化成Json对象,然后存储。
  4. 序列化成二进制:即将对象体系化成二进制字节流保存到文件中。

C#,关联知识点:

  1. 系列化与反体系化
  2. 文件流的读写
  3. ListView呈现复选框,并横向排列

正如图所示【重要功能是将用户输入的音信保存成各样格式,并从各类文档中开展读取出来】:

C# 1

保存和读取文本文档代码如下:

C# 2C# 3

 1         /// <summary>
 2         /// 保存成文本
 3         /// </summary>
 4         /// <param name="sender"></param>
 5         /// <param name="e"></param>
 6         private void btnSaveTxt_Click(object sender, EventArgs e)
 7         {
 8             Dictionary<string, string> dicInfos  = GetDictionaryInfos();
 9             string filePath = "objPerson.txt";
10             //采用using关键字,会自动释放
11             using (FileStream fs = new FileStream(filePath, FileMode.Create))
12             {
13                 using (StreamWriter sw = new StreamWriter(fs, Encoding.Default))
14                 {
15                     foreach (var keyPair in dicInfos)
16                     {
17                         sw.WriteLine(string.Format("{0}={1}", keyPair.Key, keyPair.Value));
18                     }
19                 }
20             }
21         }
22 
23         /// <summary>
24         /// 从文本中读取
25         /// </summary>
26         /// <param name="sender"></param>
27         /// <param name="e"></param>
28         private void btnReadTxt_Click(object sender, EventArgs e)
29         {
30             string filePath = "objPerson.txt";
31             Dictionary<string, string> dic = new Dictionary<string, string>();
32             //采用using关键字,会自动释放
33             using (FileStream fs = new FileStream(filePath, FileMode.Open))
34             {
35                 using (StreamReader sw = new StreamReader(fs, Encoding.Default))
36                 {
37                     while (!sw.EndOfStream) {
38                         string lineInfo = sw.ReadLine();
39                         dic.Add(lineInfo.Split('=')[0], lineInfo.Split('=')[1]);
40                     }
41                 }
42             }
43             this.txtName.Text = dic["Name"];
44             this.dtBirthday.Text = dic["Birthday"];
45             if (dic["Gender"] == this.rbBoy.Text)
46             {
47                 this.rbBoy.Checked = true;
48             }
49             else {
50                 this.rbGirl.Checked = true;
51             }
52             string[] loves = dic["Love"].Split('|');
53             foreach (var love in loves)
54             {
55                 foreach (var item in this.lsvLove.Items)
56                 {
57                     ListViewItem li = item as ListViewItem;
58                     if (li.Text == love)
59                     {
60                         li.Checked = true;
61                     }
62                 }
63             }
64         }

View Code

封存和读取Xml文档代码如下:

C# 4C# 5

 1  /// <summary>
 2         /// 保存成Xml
 3         /// </summary>
 4         /// <param name="sender"></param>
 5         /// <param name="e"></param>
 6         private void btnSaveXml_Click(object sender, EventArgs e)
 7         {
 8             Person p = GetPersonInfos();
 9             string filePath = "objPerson.xml";
10             using (FileStream fs = new FileStream(filePath, FileMode.Create))
11             {
12                 XmlSerializer serializer = new XmlSerializer(typeof(Person));
13                 serializer.Serialize(fs, p);
14             }
15         }
16 
17         /// <summary>
18         /// 从Xml中读取
19         /// </summary>
20         /// <param name="sender"></param>
21         /// <param name="e"></param>
22         private void btnReadXml_Click(object sender, EventArgs e)
23         {
24             string filePath = "objPerson.xml";
25             Person p;
26             using (FileStream fs = new FileStream(filePath, FileMode.Open))
27             {
28                 XmlSerializer serializer = new XmlSerializer(typeof(Person));
29                 object obj= serializer.Deserialize(fs);
30                 p = obj as Person;
31             }
32             SetPersonInfos(p);
33         }

View Code

保存和读取Json文档如下:

C# 6C# 7

 1    /// <summary>
 2         /// 保存成Json
 3         /// </summary>
 4         /// <param name="sender"></param>
 5         /// <param name="e"></param>
 6         private void btnSaveJson_Click(object sender, EventArgs e)
 7         {
 8             Person p = GetPersonInfos();
 9             JavaScriptSerializer jserializer = new JavaScriptSerializer();
10             string strJson = jserializer.Serialize(p);
11             string strRegex  = @"\\/Date\((\d+)\)\\/";
12             MatchEvaluator evaluator = new MatchEvaluator(ConvertJsonDateToDateString);
13 
14             //对时间进行处理,需要引用System.Text.RegularExpressions;命名空间
15             Regex reg = new Regex(strRegex);
16             strJson = reg.Replace(strJson, evaluator);
17 
18             string filePath = "objPerson.json";
19             using (FileStream fs = new FileStream(filePath, FileMode.Create))
20             {
21                 using (StreamWriter sw = new StreamWriter(fs, Encoding.Default))
22                 {
23                     sw.Write(strJson);
24                 }
25             }
26         }
27 
28         /// <summary>
29         /// 从Json中读取
30         /// </summary>
31         /// <param name="sender"></param>
32         /// <param name="e"></param>
33         private void btnReadJson_Click(object sender, EventArgs e)
34         {
35             JavaScriptSerializer jserializer = new JavaScriptSerializer();
36             string filePath = "objPerson.json";
37             Person p;
38             using (FileStream fs = new FileStream(filePath, FileMode.Open))
39             {
40                 using (StreamReader sw = new StreamReader(fs, Encoding.Default))
41                 {
42                     string strJson = sw.ReadToEnd();
43                     string strRegex = @"\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2}";
44                     MatchEvaluator evaluator = new MatchEvaluator(ConvertDateStringToJsonDate);    //对时间进行处理
45                     Regex reg = new Regex(strRegex);
46                     strJson = reg.Replace(strJson, evaluator);
47                     p = jserializer.Deserialize<Person>(strJson);
48                 }
49             }
50             SetPersonInfos(p);
51         }

View Code

封存和读取Bin文档如下:

C# 8C# 9

 1         /// <summary>
 2         /// 保存成二进制文件
 3         /// </summary>
 4         /// <param name="sender"></param>
 5         /// <param name="e"></param>
 6         private void btnSaveBin_Click(object sender, EventArgs e)
 7         {
 8             Person p = GetPersonInfos();
 9             string filePath = "objPerson.bin";
10             using (FileStream fs = new FileStream(filePath, FileMode.Create)) {
11                 BinaryFormatter bf = new BinaryFormatter();
12                 bf.Serialize(fs, p);
13             }
14         }
15 
16         /// <summary>
17         /// 读取二进制文件
18         /// </summary>
19         /// <param name="sender"></param>
20         /// <param name="e"></param>
21         private void btnReadBin_Click(object sender, EventArgs e)
22         {
23             string filePath = "objPerson.bin";
24             Person p;
25             using (FileStream fs = new FileStream(filePath, FileMode.Open))
26             {
27                 BinaryFormatter bf = new BinaryFormatter();
28                 p= bf.Deserialize(fs) as Person;
29             }
30             SetPersonInfos(p);
31         }

View Code

备注:其实对象持久化和对象连串化是五个不等的定义。两者有关联却不同。

目标持久化:是使对象足以保留到实体存储介质中,在对象生命周期截至后方可复出。

目的系列化:是将目的或者数据结构转化成特定的格式,使其可在网络中传输,或者可存储在内存还是文件中。

 

相关文章