.NET中的序列化

来源:互联网 发布:广电网络的电话是多少 编辑:程序博客网 时间:2024/06/03 22:40
.NET中的序列化分为三类:二进制,Soap,XML。三个进行序列化/反序列化的类分别是System.Runtime.Serialization.Formatters.Binary.BinaryFormatter,System.Runtime.Serialization.Formatters.Soap.SoapFormatter和System.Xml.Serialization.XmlSerializer。 
  
        BinaryFormatter用于ASP.NET中的ViewState保存和恢复,以及Remoting中TcpChannel的默认Formatter,SoapFormatter用于Remoting中HttpChannel的默认Formatter,而XmlSerializer用于.NET中的Web Service。虽然SoapFormatter产生的也是XML格式的字符流,但其中包含了Soap协议所需要的一些数据,因此比XmlSerializer产生的数据量要大,这也是Web Service比使用HttpChannel+SoapFormatter的Remoting效率要好的原因。 


        使用SoapFormatter和XmlSerializer序列化时,类需要提供public的无参构造函数,BinaryFormatter则无此需要。


        BinnaryFormatter默认序列化类实例的所有字段,而SoapFormatter和XmlSerializer默认只序列化类实例的所有public的字段和属性,并且属性要同时提供get和set方法。 


        BinaryFormatter可以完整的保存序列化对象的类型信息,包含Assembly, 版本号等。而SoapFormatter的类型相比弱一些,虽然要求限定名一致,但实际上序列化和反序列化后的对象可以有很大不同,比如处于不同的Assembly,私有字段有一些区别等。XmlSerializer则只需要格式兼容,即完全有可能从NamespaceA.ClassA序列化出的Xml反序列化为NamespaceB.ClassB的实例。 


        支持BinnaryFormatter的类需要添加SerializableAttribute,对于序列化过程的控制,有四种方式: 

为不需要序列化的字段添加NonSerializedAttribute。 
实现接口ISerializable,自定义序列化和反序列化过程。 
实现接口IDeserializationCallback。 
为BinnaryFormatter的实例设置自定义的Binder. 
        支持SoapFormatter的类,对于序列化过程的控制,有三种方式:

为字段或局性添加相应的SoapXXXAttribute,比如SoapIgnoreAttribute, SoapElementAttribute, SoapAttributeAttribute等。 
实现接口IDeserialilzationCallback. 
为BinnaryFormatter的实例设置自定义的Binder. 
        支持XmlSerializer的类,对于序列化过程的控制,有四种方式:

为字段或局性添加相应的XmlXXXAttribute,比如XmlIgnoreAttribute, XmlElementAttribute, XmlAttributeAttribute等。 
实现接口IXmlSerializable(不推荐)。 
实现接口IDeserialilzationCallback。 
创建XmlSerializer时指定XmlTypeMapping或XmlAttributeOverrides。 
        本文仅给出介绍,有关如何在代码中实现对序列化/反序列化过程的控制,请参考.NET文档。
原创粉丝点击