通州北大青鳥校區(qū)學(xué)術(shù)部丁老師介紹:如果你希望讓用戶對類進行串行化,但是對數(shù)據(jù)流的組織方式不完全滿意,那么可以通過在自定義類中實現(xiàn)接口來自定義串行化行為。這個接口只有一個方法,GetObjectData. 這個方法用于將對類對象進行串行化所需要的數(shù)據(jù)填進SerializationInfo對象。你使用的格式化器將構(gòu)造SerializationInfo對象,然后在串行化時調(diào)用GetObjectData. 如果類的父類也實現(xiàn)了ISerializable,那么應(yīng)該調(diào)用GetObjectData的父類實現(xiàn)。
如果你實現(xiàn)了ISerializable,那么還必須提供一個具有特定原型的構(gòu)造器,這個構(gòu)造器的參數(shù)列表必須與GetObjectData相同。這個構(gòu)造器應(yīng)該被聲明為私有的或受保護的,以防止粗心的開發(fā)人員直接使用它。
示例如下:
實現(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 的摘要說明
/// </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ù)部提供