.net序列化和反序列化

来源:互联网 发布:263网络集团 编辑:程序博客网 时间:2024/04/26 06:41
  1. .net c# 序列化和反序列
  2.   所谓的序列化就是是将对象转换为容易传输的格式的过程,一般情况下转化打流文件,放入内存或者IO文件中。例如,可以序列化一个对象,然后使用 HTTP 通过 Internet 在客户端和服务器之间传输该对象,或者和其它应用程序共享使用。反之,反序列化根据流重新构造对象。
  3.    
  4.   .NET自带的有两种序列化对象的方式,Xml和binary的,XML 序列化不转换方法、索引器、私有字段或只读属性(只读集合除外)。要序列化对象的所有字段和属性(公共的和私有的),请使用 BinaryFormatter,而不要使用 XML 序列化(参见ms-help://MS.NETFramework.v20.chs/dv_fxserialization/html/8c63200d-db63-4a03-a93d-21641623df62.htm)
  5. XML 和 SOAP 序列化
  6.    两者的程序处理方式基本一致,都是基于工厂模式的,下面我就只说二进制的序列化的方式:
  7.    例如我们有个对象: 
  8.  [Serializable]
  9. public class ClassToSerialize{
  10.     public int id=100;
  11.     public string name="Name";
  12. }
  13.    
  14. 需要序列化该对象,必须在给该类加上Serializable的属性,然后创建一个序列化写入的流: 
  15. FileStream fileStream = new FileStream("temp.dat", FileMode.Create);
  16. 然后创建二进制格式器: 
  17. BinaryFormatter b=new BinaryFormatter();
  18. 然后是序列化: 
  19. b.Serialize(fileStream,c);
  20. ,然后关闭保存流。(可以见下面的例子)
  21.   
  22.    读取一个已经被序列化的对象的时候:操作方式一样,只是 
  23. FileStream fileStream = new FileStream("temp.dat", FileMode.Open, FileAccess.Read, FileShare.Read);
  24. ClassToSerialize c =(ClassToSerialize)b.Deserialize(fileStream);
  25. 然后就可以读取了,完整的例子是: 
  26. using System;
  27. using System.IO;
  28. using System.Runtime.Serialization;
  29. using System.Runtime.Serialization.Formatters.Binary;
  30. public class SerialTest{
  31.     public void SerializeNow(){
  32.         ClassToSerialize c=new ClassToSerialize();
  33.         FileStream fileStream = new FileStream("temp.dat", FileMode.Create);
  34.         BinaryFormatter b=new BinaryFormatter();
  35.         b.Serialize(fileStream,c);
  36.         fileStream.Close();
  37.     }
  38.     public void DeSerializeNow(){
  39.         ClassToSerialize c=new ClassToSerialize();
  40.         FileStream fileStream = new FileStream("temp.dat", FileMode.Open, FileAccess.Read, FileShare.Read);
  41.         BinaryFormatter b=new BinaryFormatter();//SoapFormatter
  42.         c=(ClassToSerialize)b.Deserialize(fileStream);
  43.         Console.WriteLine(c.name);
  44.         fileStream.Close();
  45.     }
  46.     public static void Main(string[] s){
  47.         SerialTest st=new SerialTest();
  48.         st.SerializeNow();
  49.         st.DeSerializeNow();
  50.     }
  51. }
  52. [Serializable]
  53. public class ClassToSerialize{
  54.     public int id=100;
  55.     public string name="Name";
  56. }
  57. 这就是自带的序列化和反序列的操作,但是,很多情况下,一个对象比较大,而且很多私有的属性和方法我们不需要,例如在原型模式里面序列化的话,只需要序列Clone方法和一些属性,私有的方法无需要,还例如在读取大规模的IO的时候,读取操作完全不需要... 这时候就需要自己集成重写序列的ISerializable接口:
  58.  实现该接口需要两个注意的,一个就是构造函数,主要是为了反序列,另一个就是GetObjectData,主要是执行序列化,例如我们现在有一个Employee类需要序列化 
  59.     [Serializable()]    //Set this attribute to all the classes that want to serialize
  60.     public class Employee : ISerializable //derive your class from ISerializable {
  61.         public int EmpId;
  62.         public string EmpName;
  63.         [NonSerialized()]
  64.     public string NoSerialString="NoSerialString-Test";
  65. }
  66. ,需要注意的是我这里的NoSerialString属性前面有[NonSerialized()],就是说默认并不序列化这个属性,而是使用默认值 。
  67.  首先是构造函数: 
  68.         public Employee(SerializationInfo info, StreamingContext ctxt)
  69.         {
  70.             EmpId = (int)info.GetValue("EmployeeId"typeof(int));
  71.             EmpName = (String)info.GetValue("EmployeeName"typeof(string));
  72.             //NoSerialString = (String)info.GetValue("NoSerialString", typeof(string));
  73.         }
  74. 然后是序列化方法,就是当写入流的时候怎么保存的:
  75.         public void GetObjectData(SerializationInfo info, StreamingContext ctxt)
  76.         {
  77.             //You can use any custom name for your name-value pair. But make sure you
  78.             // read the values with the same name. For ex:- If you write EmpId as "EmployeeId"
  79.             // then you should read the same with "EmployeeId"
  80.             info.AddValue("EmployeeId", EmpId);
  81.             info.AddValue("EmployeeName", EmpName);
  82.         }
  83. 把上面两个方法写入到Employee类,然后写个测试的程序:
  84. public class ObjSerial{
  85.     public static void Main(String[] args){
  86.         Employee mp = new Employee();
  87.         mp.EmpId = 10;
  88.         mp.EmpName = "Omkumar";
  89.         mp.NoSerialString = "你好啊";
  90.                 
  91.        //序列化
  92.         Stream stream = File.Open("EmployeeInfo.osl", FileMode.Create);
  93.         BinaryFormatter bformatter = new BinaryFormatter();
  94.                 
  95.         Console.WriteLine("Writing Employee Information");
  96.         bformatter.Serialize(stream, mp);
  97.         stream.Close();
  98.         mp = null;
  99.        //反序列
  100.         stream = File.Open("EmployeeInfo.osl", FileMode.Open);
  101.         bformatter = new BinaryFormatter();
  102.             
  103.         Console.WriteLine("Reading Employee Information");
  104.         mp = (Employee)bformatter.Deserialize(stream);
  105.         stream.Close();
  106.                 
  107.         Console.WriteLine("Employee Id: {0}",mp.EmpId.ToString());
  108.         Console.WriteLine("Employee Name: {0}",mp.EmpName);
  109.         Console.WriteLine("Employee NoSerialString: {0}",mp.NoSerialString);
  110.     }
  111. }
  112. 执行的结果是: 
  113. Writing Employee Information
  114. Reading Employee Information
  115. Employee Id: 10
  116. Employee Name: Omkumar
  117. Employee NoSerialString: NoSerialString-Test
  118.  看到Employee NoSerialString:属性的值没有,它保持默认值,没有序列化。
原创粉丝点击