C# 序列化 Serialize 的应用

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.IO;
 6 using System.Runtime.Serialization.Formatters.Binary;
 7 
 8 namespace SerializeTest
 9 {
10     class Program
11     {
12         static void Main(string[] args) {
13             // Create a Person 
14             Person ztc = new Person("ZhouTianChi", 32);
15 
16             // Serialize 将这个 Person 类的实例,写入到硬盘中保存
17             using (FileStream fs = File.Create(@"D:\person.txt")) {
18                 // 使用的是 BinaryFormatter 类
19                 BinaryFormatter bf = new BinaryFormatter();
20                 // 的Serialize 方法
21                 bf.Serialize(fs, ztc);
22             }
23 
24             // 声音一个空的 Person 类,用来装载我们反Serialize后得到的对象 
25             Person DeSerializeZTC;
26             // DeSerialize
27             using (FileStream fs = File.Open(@"D:\person.txt",FileMode.Open)) {
28                 // 使用 BinaryFormatter 类
29                 BinaryFormatter bf = new BinaryFormatter();
30                 // 的 Deserialize 方法
31                 DeSerializeZTC = (Person)bf.Deserialize(fs);
32 
33                 DeSerializeZTC.SayHello();
34             }
35         }
36     }
37 
38     // 这里我们定义一个 类, (可序列化的类,就是把类中的数据弄成流的形式)
39     [Serializable]
40     class Person {
41         // NonSerialized 就是不将这个字段序列化.
42         [NonSerialized]
43         public string test = "asldkgjweg";
44 
45         public int Age { get; set; }
46         public string Name { get; set; }
47         public Person(string name, int age) {
48             this.Age = age;
49             this.Name = name;
50         }
51         public void SayHello() {
52             Console.WriteLine("I am " + Name + ". And " + Age + " years old.");
53         }
54     }
55 }


Serialized 序列化 , 就是把类中的数据转化成流的形式. 这样, 可以存在硬盘中, 也可以在网络间传送.

posted @ 2013-06-23 17:31  easyfrog  阅读(1045)  评论(0编辑  收藏  举报