![]()
1 using System;
2 using System.Collections.Generic;
3 using System.IO;
4 using System.Linq;
5 using System.Runtime.Serialization;
6 using System.Runtime.Serialization.Formatters.Binary;
7 using System.Text;
8 using System.Threading.Tasks;
9
10 namespace _06序列化和反序列化
11 {
12 class Program
13 {
14 static void Main(string[] args)
15 {
16 //序列化:把一个对象变成二进制
17 //反序列化:把二进制转换成对象
18
19 ////序列化
20 //Peson p = new Peson();
21
22 //p.Count = "小王";
23 //p.Pass = 10;
24 //using (FileStream fs = new FileStream(@"C:\Users\Administrator\Desktop\1.txt", FileMode.OpenOrCreate, FileAccess.Write))
25 //{
26 // BinaryFormatter bf = new BinaryFormatter();//开始序列化
27 // bf.Serialize(fs, p);
28 //}
29 //Console.WriteLine("序列化成功");
30
31 //反序列化
32 using (FileStream fls = new FileStream(@"C:\Users\Administrator\Desktop\1.txt", FileMode.OpenOrCreate, FileAccess.Read))
33 {
34 BinaryFormatter bif = new BinaryFormatter();//开始反序列化
35 Peson s = bif.Deserialize(fls) as Peson;
36 Console.WriteLine(s.Count);
37 Console.WriteLine(s.Pass);
38 }
39 }
40 }
41 [Serializable]//添加一个特性,表明该类可以被序列化
42 public class Peson
43 {
44 string count;
45 int pass;
46
47 public string Count { get => count; set => count = value; }
48 public int Pass { get => pass; set => pass = value; }
49 }
50 }