近期看了大量关于WCF的资料,深入的了解了关于WCF的原理机制,我们都知道,WCF内置了两种序列化方式,DataContractSerializer和NetDataContractSerializer。现在就和大家简单的分析介绍一下WCF序列化方面的知识吧。
先来看看WCF序列化的声明:
- public sealed class DataContractSerializer : XmlObjectSerializer
- {
- public DataContractSerializer(Type type);
- …
- public override object ReadObject(XmlReader reader);
- public object ReadObject(Stream stream);
- public void WriteObject(Stream stream, object graph);
- public override void WriteObject(XmlWriter writer, object graph);
- …
- }
- public sealed class NetDataContractSerializer : XmlObjectSerializer, IFormatter
- {
- public NetDataContractSerializer();
- …
- public object Deserialize(Stream stream);
- public void Serialize(Stream stream, object graph);
- public override object ReadObject(XmlReader reader);
- public object ReadObject(Stream stream);
- public void WriteObject(Stream stream, object graph);
- public override void WriteObject(XmlWriter writer, object graph);
- …
- }
#T#其中两者的ReadObject(Straem)、WriteObject(Stream, object)的实现继承自基类XmlObjectSerializer,其他方法均为已覆写或实现。从两个类型的声明中可以看出NetDataContractSerializer实现了IFormatter接口,而 DataContractSerializer没有,因此只有NetDataContractSerializer能使用.NET基础结构中的序列化,而 DataContractSerializer则是专用于WCF的。还有一个细节DataContractSerializer的Constructor有一个Type类型的参数,而NetDataContractSerializer没有。这可蕴藏着深意啊,读者接着看就明白了。