XmlSerializer 和 BinaryFormatter 之间有什么区别 [英] What are the differences between the XmlSerializer and BinaryFormatter

查看:19
本文介绍了XmlSerializer 和 BinaryFormatter 之间有什么区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

上周我花了很多时间进行序列化.在那段时间里,我发现了许多使用 BinaryFormatter 或 XmlSerializer 的示例.不幸的是,我没有找到任何全面详细说明两者差异的例子.

I spent a good portion of time last week working on serialization. During that time I found many examples utilizing either the BinaryFormatter or XmlSerializer. Unfortunately, what I did not find were any examples comprehensively detailing the differences between the two.

我好奇的根源在于为什么 BinaryFormatter 能够直接反序列化到接口,而 XmlSerializer 则不能.Jon Skeet 在回答在运行时转换为多个(未知类型)" 提供了一个直接二进制序列化到接口的示例.Stan R. 在他对XML 对象反序列化到接口."

The genesis of my curiosity lies in why the BinaryFormatter is able to deserialize directly to an interface whilst the XmlSerializer is not. Jon Skeet in an answer to "casting to multiple (unknown types) at runtime" provides an example of direct binary serialization to an interface. Stan R. provided me with the means of accomplishing my goal using the XmlSerializer in his answer to "XML Object Deserialization to Interface."

除了明显的 BinaryFormatter 使用二进制序列化,而 XmlSerializer 使用 XML 我想更全面地了解基本差异.何时使用一种或另一种以及每种的优缺点.

Beyond the obvious of the BinaryFormatter utilizes binary serialization whilst the XmlSerializer uses XML I'd like to more fully understand the fundamental differences. When to use one or the other and the pros and cons of each.

推荐答案

二进制格式化程序能够直接反序列化为接口类型的原因是因为当对象最初序列化为包含类型和程序集信息的二进制流元数据时坚持使用对象数据.这意味着当二进制格式化程序反序列化对象时,它知道它的类型,构建正确的对象,然后您可以将其转换为对象实现的接口类型.

The reason a binary formatter is able to deserialize directly to an interface type is because when an object is originally serialized to a binary stream metadata containing type and assembly information is stuck in with the object data. This means that when the binary formatter deserializes the object it knows its type, builds the correct object and you can then cast that to an interface type that object implements.

另一方面,XML 序列化器只是序列化为模式,并且仅序列化对象的公共字段和值,除此之外没有其他类型信息(例如,类型实现的接口).

The XML serializer on the otherhand just serializes to a schema and only serializes the public fields and values of the object and no type information other then that (e.g. interfaces the type implements).

这是一篇很好的帖子,.NET Serialization,比较了BinaryFormatterSoapFormatterXmlSerializer.我建议您查看下表,除了前面提到的序列化程序外,还包括 DataContractSerializerNetDataContractSerializerprotobuf-net.

Here is a good post, .NET Serialization, comparing the BinaryFormatter, SoapFormatter, and XmlSerializer. I recommend you look at the following table which in addition to the previously mentioned serializers includes the DataContractSerializer, NetDataContractSerializer and protobuf-net.

这篇关于XmlSerializer 和 BinaryFormatter 之间有什么区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆