我们可以通过给类添加Serializable特性,使其可以序列化与反序列化.通俗的说,就是能将这个类的对象信息保存到本地,也可以通过保存到本地的对象信息实例化对象.
首先,写一个Utils工具类来实现序列化与反序列化:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43 1using System;
2using System.Collections.Generic;
3using System.Linq;
4using System.Text;
5using System.Threading.Tasks;
6using System.Runtime.Serialization.Formatters.Binary;
7using System.IO;
8
9namespace ConsoleApplication1
10{
11 class Utils
12 {
13 private BinaryFormatter bf;
14
15 public Utils ()
16 {
17 bf = new BinaryFormatter();
18 }
19
20 public void Serialize<T> (string path, T obj) where T: class
21 {
22 FileStream fs = new FileStream(path, FileMode.OpenOrCreate);
23 bf.Serialize(fs, obj);
24 fs.Close();
25 }
26
27 public T Deserialize<T>(string path) where T : class
28 {
29 if (!File.Exists (path))
30 {
31 Console.WriteLine("文件不存在: {0}", path);
32 return null;
33 }
34
35 FileStream fs = new FileStream(path, FileMode.Open);
36 T obj = bf.Deserialize(fs) as T;
37 fs.Close();
38 return obj;
39 }
40 }
41}
42
43
写一个测试类Person:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29 1using System;
2using System.Collections.Generic;
3using System.Linq;
4using System.Text;
5using System.Threading.Tasks;
6
7namespace ConsoleApplication1
8{
9 [Serializable]
10 class Person
11 {
12 private string flag;
13 public string Flag
14 {
15 get
16 {
17 return flag;
18 }
19 set
20 {
21 flag = value;
22 }
23 }
24
25 public string name;
26 }
27}
28
29
测试:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30 1#define debug
2
3using System;
4using System.Collections.Generic;
5using System.Linq;
6using System.Text;
7using System.Threading.Tasks;
8
9namespace ConsoleApplication1
10{
11 class Program
12 {
13 static void Main(string[] args)
14 {
15 string path = @"E:\Person.txt";
16
17 Person p = new Person();
18 p.name = "王二狗";
19 p.Flag = "大家好,我是flag";
20
21 Utils utils = new Utils();
22 utils.Serialize<Person>(path, p);
23
24 Person p2 = utils.Deserialize<Person>(path);
25 Console.WriteLine("p2.name: {0}, p2.Flag: {1}", p2.name, p2.Flag);
26 }
27 }
28}
29
30
项目中用来存储进度信息蛮好用的.