我們可以實現ISerializable介面來自訂序列化行為。這個介面只有一個方法GetObjectData。這個方法用於將對類對象進行序列化所需的資料填進SerializationInfo對象。你使用的格式化器(比如BinaryFormatter)將構造SerializationInfo對象,然後在序列化時調用GetObjectData。因此,你需要實現GetObjectData,讓它添加你從類中選擇的值,並且映射到你選擇的字串名。注意,如果類的父類也實現ISerializable,那麼應該調用GetObjectData的父類實現。
給出例子:using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
[Serializable]
public class Insect : ISerializable
{
private string name;
private int id;
public Insect(string name, int id)
{
this.name = name;
this.id = id;
}
public override string ToString()
{
return String.Format("{0}:{1}", name, id);
}
public Insect(){}
public virtual void GetObjectData(SerializationInfo s, StreamingContext c)
{
s.AddValue("CommonName", name);
s.AddValue("ID#", id);
}
private Insect(SerializationInfo s, StreamingContext c)
{
name = s.GetString("CommonName");
id = s.GetInt32("ID#");
}
}
class ImpISerialApp
{
static void Main(string[] args)
{
Insect i = new Insect("Meadow Brown", 12);
Stream s = File.Create("Insect.bin");
BinaryFormatter b = new BinaryFormatter();
b.Serialize(s, i);
s.Seek(0, SeekOrigin.Begin);
Insect j = (Insect)b.Deserialize(s);
s.Close();
Console.WriteLine(j);
}
}
Insect.bin包含以下資訊:
DISerializable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null Insect
CommonName ID# Meadow Brown