【学习历程05】序列化和反序列化

 1  class Program
 2     {
 3         static void Main(string[] args)
 4         {
 5            //序列化:将数据转换为二进制
 6            //反序列化:将二进制转换为数据
 7            //序列化的作用:传递数据
 8             Person p = new Person();
 9             Person p2 = new Person();
10             p.Name ="张三";
11             p.Age = 18;
12             using (FileStream fswrite=new FileStream(@"C:UsersAdministratorDesktop1.txt",FileMode.OpenOrCreate,FileAccess.ReadWrite))
13             {
14                //开始序列化对象
15                 BinaryFormatter bf = new BinaryFormatter();
16                 bf.Serialize(fswrite, p);
17             }
18 
19             //反序列化
20             using (FileStream fswrite = new FileStream(@"C:UsersAdministratorDesktop1.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite))
21             {
22                 //开始序列化对象
23                 BinaryFormatter bf2 = new BinaryFormatter();
24                 p2=(Person)bf2.Deserialize(fswrite);
25             }
26             Console.WriteLine(p2.Name);
27             Console.WriteLine(p2.Age);
28             Console.ReadKey();
29         }  
30     }
31 
32     //指定一个类可以序列化
33     [Serializable]
34     public class Person
35     {
36         private string _name;
37         public string Name
38         {
39             get { return _name; }
40             set { _name = value; }
41         }
42 
43         private int _age;
44         public int Age
45         {
46             get { return _age; }
47             set { _age = value; }
48         }
49     }
原文地址:https://www.cnblogs.com/ncy123/p/13290124.html