我们可以实现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
![ExpandedBlockStart.gif](/Images/OutliningIndicators/ExpandedBlockStart.gif)
{
private string name;
private int id;
public Insect(string name, int id)
![ExpandedSubBlockStart.gif](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
this.name = name;
this.id = id;
}
public override string ToString()
![ExpandedSubBlockStart.gif](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
return String.Format("{0}:{1}", name, id);
}
![ExpandedSubBlockStart.gif](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
public Insect()
{}
public virtual void GetObjectData(SerializationInfo s, StreamingContext c)
![ExpandedSubBlockStart.gif](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
s.AddValue("CommonName", name);
s.AddValue("ID#", id);
}
private Insect(SerializationInfo s, StreamingContext c)
![ExpandedSubBlockStart.gif](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
name = s.GetString("CommonName");
id = s.GetInt32("ID#");
}
}
![None.gif](/Images/OutliningIndicators/None.gif)
class
ImpISerialApp
![ExpandedBlockStart.gif](/Images/OutliningIndicators/ExpandedBlockStart.gif)
{
static void Main(string[] args)
![ExpandedSubBlockStart.gif](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
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