通州北大青鸟校区讲解:自定义序列化

通州北大青鸟校区学术部丁老师介绍:如果你希望让用户对类进行串行化,但是对数据流的组织方式不完全满意,那么可以通过在自定义类中实现接口来自定义串行化行为。这个接口只有一个方法,GetObjectData. 这个方法用于将对类对象进行串行化所需要的数据填进SerializationInfo对象。你使用的格式化器将构造SerializationInfo对象,然后在串行化时调用GetObjectData. 如果类的父类也实现了ISerializable,那么应该调用GetObjectData的父类实现。

如果你实现了ISerializable,那么还必须提供一个具有特定原型的构造器,这个构造器的参数列表必须与GetObjectData相同。这个构造器应该被声明为私有的或受保护的,以防止粗心的开发人员直接使用它。

示例如下:
实现ISerializable的类:
(通州北大青鸟校区)    
 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 的摘要说明
 /// </summary>
 [Serializable]
 public class Employee:ISerializable
  {
     public int EmpId=100;
     public string EmpName="刘德华";
     [NonSerialized]
     public string NoSerialString = "NoSerialString-Test";
     public Employee()
      {
         //
         // TODO: 在此处添加构造函数逻辑
         //
     }
     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);
     }
 }(通州北大青鸟校区
 

    序列化和反序列化方法:
 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);
     }
通州北大青鸟校区学术部提供

北大青鸟网上报名
北大青鸟招生简章