通州北大青鳥校區學術部丁老師介紹:如果你希望讓用戶對類進行串行化,但是對數據流的組織方式不完全滿意,那么可以通過在自定義類中實現接口來自定義串行化行為。這個接口只有一個方法,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);
}
通州北大青鳥校區學術部提供