通州北大青鳥校區(qū)講解:自定義序列化

通州北大青鳥校區(qū)學(xué)術(shù)部丁老師介紹:如果你希望讓用戶對(duì)類進(jìn)行串行化,但是對(duì)數(shù)據(jù)流的組織方式不完全滿意,那么可以通過(guò)在自定義類中實(shí)現(xiàn)接口來(lái)自定義串行化行為。這個(gè)接口只有一個(gè)方法,GetObjectData. 這個(gè)方法用于將對(duì)類對(duì)象進(jìn)行串行化所需要的數(shù)據(jù)填進(jìn)SerializationInfo對(duì)象。你使用的格式化器將構(gòu)造SerializationInfo對(duì)象,然后在串行化時(shí)調(diào)用GetObjectData. 如果類的父類也實(shí)現(xiàn)了ISerializable,那么應(yīng)該調(diào)用GetObjectData的父類實(shí)現(xiàn)。

如果你實(shí)現(xiàn)了ISerializable,那么還必須提供一個(gè)具有特定原型的構(gòu)造器,這個(gè)構(gòu)造器的參數(shù)列表必須與GetObjectData相同。這個(gè)構(gòu)造器應(yīng)該被聲明為私有的或受保護(hù)的,以防止粗心的開發(fā)人員直接使用它。

示例如下:
實(shí)現(xiàn)ISerializable的類:
(通州北大青鳥校區(qū))    
 using System;
 using System.Data;
 using System.Configuration;
 using System.Web;
 using System.Web.Security;
 using System.Web.UI;
 using System.Web.UI.WebControls;
 using System.Web.UI.WebControls.WebParts;
 using System.Web.UI.HtmlControls;
 using System.Runtime.Serialization;
 using System.Runtime.Serialization.Formatters.Binary;
  /// <summary>
 /// Employee 的摘要說(shuō)明
 /// </summary>
 [Serializable]
 public class Employee:ISerializable
  {
     public int EmpId=100;
     public string EmpName="劉德華";
     [NonSerialized]
     public string NoSerialString = "NoSerialString-Test";
     public Employee()
      {
         //
         // TODO: 在此處添加構(gòu)造函數(shù)邏輯
         //
     }
     private Employee(SerializationInfo info, StreamingContext ctxt)
      {
         EmpId = (int)info.GetValue("EmployeeId", typeof(int));
         EmpName = (String)info.GetValue("EmployeeName",typeof(string));
         //NoSerialString = (String)info.GetValue("EmployeeString",typeof(string));
     }
     public void GetObjectData(SerializationInfo info, StreamingContext ctxt)
      {
         info.AddValue("EmployeeId", EmpId);
         info.AddValue("EmployeeName", EmpName);
         //info.AddValue("EmployeeString", NoSerialString);
     }
 }(通州北大青鳥校區(qū)
 

    序列化和反序列化方法:
 public void OtherEmployeeClassTest()
      {
         Employee mp = new Employee();
         mp.EmpId = 10;
         mp.EmpName = "邱楓";
         mp.NoSerialString = "你好呀";
         Stream steam = File.Open("c:\\temp3.dat", FileMode.Create);
         BinaryFormatter bf = new BinaryFormatter();
         Response.Write("Writing Employee Info:");
         bf.Serialize(steam,mp);
         steam.Close();
         mp = null;
         //反序列化
         Stream steam2 = File.Open("c:\\temp3.dat", FileMode.Open);
         BinaryFormatter bf2 = new BinaryFormatter();
         Response.Write("Reading Employee Info:");
         Employee mp2 = (Employee)bf2.Deserialize(steam2);
         steam2.Close();
         Response.Write(mp2.EmpId);
         Response.Write(mp2.EmpName);
         Response.Write(mp2.NoSerialString);
     }
通州北大青鳥校區(qū)學(xué)術(shù)部提供

北大青鳥網(wǎng)上報(bào)名
北大青鳥招生簡(jiǎn)章