我们可以实现ISerializable接口来自定义串行化行为。这个接口只有一个方法GetObjectData。这个方法用于将对类对象进行序列化所需的数据填进SerializationInfo对象。你使用的格式化器(比如BinaryFormatter)将构造SerializationInfo对象,然后在序列化时调用GetObjectData。因此,你需要实现GetObjectData,让它添加你从类中选择的值,并且映射到你选择的字符串名。注意,如果类的父类也实现ISerializable,那么应该调用GetObjectData的父类实现。
给出例子:
Insect.bin包含以下信息:
DISerializable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null Insect
CommonName ID# Meadow Brown
给出例子:
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);
}
}
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