序列化:

就是将对象的状态永久保存到某舟介质上面序列化:就是将对象的状态永久保存到某舟介质上面

//如果一个类要被序列化 必须标记为可序列化

//被序列化的类里面的字段也必须要标记为可序列化

//字段的父类也要标记为可序列化

//int string 等本身已经被标记为可序列化

View Code
 1             //序列化:就是将对象的状态永久保存到某舟介质上面
 2             Person myp = new Person();
 3             myp.Age = 19;
 4             myp.Name = "chen";
 5             //File.WriteAllLines("1.txt", new string[] { myp.Name +":"+ myp.Age });
 6             //MessageBox.Show(File.ReadAllLines("1.txt")[0]);
 7 
 8             #region 序列化
 9             using (FileStream stream = new FileStream("sel.bin", FileMode.Create))
10             {
11                 //创建一个二进制格式化器             
12                 System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
13                 //调用序列化方法
14                 bf.Serialize(stream, myp);
15             } 
16             #endregion
17             #region 反序列化
18             using (FileStream stream = new FileStream("sel.bin", FileMode.Open))
19             {
20                 //创建一个二进制格式化器             
21                 System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bff = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
22                 //调用反序列化方法
23                 Person pp = bff.Deserialize(stream) as Person;
24                 MessageBox.Show(pp.Name);
25             } 
26             #endregion
27 
28 
29 
30 
31     //如果一个类要被序列化 必须标记为可序列化
32     //被序列化的类里面的字段也必须要标记为可序列化
33     //字段的父类也要标记为可序列化
34     //int string 等本身已经被标记为可序列化
35     [Serializable] //标记 特性 可以序列化
36     class Person
37     {
38     
39         public string Name { get; set; }
40         public int Age { get; set; }
41         public Dog myDog { get; set; }
42 
43 }
44     [Serializable]
45     class Dog : Animal
46     {
47 }
48     [Serializable]
49     class Animal
50     {
51     }

 

posted on 2013-01-02 23:59  陈谨  阅读(134)  评论(0编辑  收藏  举报