首页 > 代码库 > 序列化

序列化

?
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
44
class Program
{
    static void Main(string[] args)
    {
        //需要将对象的状态保存起来  持久化
        //序列化:  将对象的状态持久化到某1中设备上(磁盘.)
        //要将类标记为Serializable 这个类的对象才可以被序列化
        //以二进制的方式序列化  而不是文本文档.
        //反序列化.  将之前序列化的文件还原为对象
 
        //Person p = new Person() { Age = 12, Name = "rose" };
        //System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
        //using (FileStream fs = new FileStream("se.bin", FileMode.Create))
        //{
        //    bf.Serialize(fs, p);
        //}
        //极品飞车
 
        System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
        using (FileStream fs = new FileStream("se.bin", FileMode.Open))
        {
            object obj = bf.Deserialize(fs);
            Person p = obj as Person;
            Console.WriteLine(p.Name + ":" + p.Age);
        }
 
        //Person p = new Person();
        //if (File.Exists("1.txt"))
        //{
        //    string[] lines = File.ReadAllLines("1.txt", Encoding.Default);
        //    p.Age = int.Parse(lines[0]);
        //    p.Name = lines[1];
        //}
        //else
        //{
        //    p.Age = 17;
        //    p.Name = "jack";
        //    File.WriteAllLines("1.txt", new string[] { p.Age.ToString(), p.Name });
        //}
        //Console.WriteLine(p.Age+":"+p.Name);
 
        Console.ReadKey();
    }
}