.net 自定义类的序列化
.net中与序列化相关的类有SerializableAttribute,NonSerializedAttribute,IFormatter,BinaryFormatter,SoapFormatter,ISerializable等。
.net框架序列化的实现方式与MFC,Delphi的实现方式不同。任何一个用户自定义类,只要用SerializableAttribute标示,则就已经能够进行序列化了,不用用户实现特定的Serialize/Deserialize函数。在一个类中,如果有不想序列化的Field(包括Property, Delegate,Event等),可以用NonSerializedAttribute来标示。具体实现序列化还需要用到实现了IFormatter接口的类。IFormatter接口包括Serialize()/Deserialize()函数,用以实现序列化过程。.net下实现IFormatter接口的类有BinaryFormatter和SoapFormatter,分别用于以二进制或SOAP的形式序列化对象。下面是一个例子:
public class Class1
{
public static void Main()
{
BinaryFormatter formatter=new BinaryFormatter();
Stream s=File.Create("SerializeFile.dat");
Person p=new Person();
p.birth=DateTime.Parse("1980-04-13 22:22:22");
p.id=1;
p.name="xuhx";
p.yearsOld=24;
formatter.Serialize(s,p);
s.Close();
}
}
[Serializable]
public class Person
{
public int id;
public string name;
public DateTime birth;
[NonSerialized]
public int yearsOld;
}
后记:只要类用SerializableAttribute标示,.net自动为类提供序列化的功能,并提供默认的序列化行为。如果用户想改变序列化的行为,可以实现ISerilizable接口(也还没有详细研究)。在序列化过程中,存储了数据,也存储了数据的类型信息,可以通过流重建此对象。