自定义序列化
简介: 控制某种类型的序列化和反序列化的过程叫做自定义序列化,通过控制序列化可以确保序列化的兼容性,可以再不同的版本之间进行序列化和反序列化,但是不会破坏该类型的核心功能。
概括:OnDeserializedAttribute、OndeserializingAttribute、OnserializedAttribute、OnSerializingAttribute这些属性可以使类型参与序列化和反序列化的全部阶段,在每个阶段可以调用该类型的方法,每个方法在层级结构中从基础到派生程序最大依次调用。控制序列化的一种方式是在对象上实现,使用Iserializable接口。
目的:是类型可以在不同的版本之间可以序列化和反序列化。
解决问题:解决了序列化的兼容性问题。
代码:
Public class Myobject:Iserializable
{
Public int n1;
Public int n2;
Public string str;
Public Myobject()
{
}
Protected MyObject(SerializationInfo info, StreamingContext context)
{
n1=info.GetInt32(“i”);
N2=info.GetInt32(“j”);
Str=info.GetString(“k”);
}
[SecurityPermissionAttribute(SecurityAction.Demand,SerializationFormatter=true)]
Public birtual void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue(“i”,n1);
info.AddValue(“j”,n2);
info.AddValue(“k”,n3);
}
}