二进制序列化Binary serialization

可以将序列化定义为一个将对象状态存储到存储介质的过程。Serialization can be defined as the process of storing the state of an object to a storage medium. 在这个过程中,对象的公共字段和私有字段以及类(包括含有该类的程序集)的名称,将转换成字节流,而字节流接着将写入数据流。During this process, the public and private fields of the object and the name of the class, including the assembly containing the class, are converted to a stream of bytes, which is then written to a data stream. 随后对该对象进行反序列化时,将创建原始对象的准确克隆。When the object is subsequently deserialized, an exact clone of the original object is created.

在面向对象的环境中实现序列化机制时,必须多在易用性与灵活性之间做出权衡。When implementing a serialization mechanism in an object-oriented environment, you have to make a number of tradeoffs between ease of use and flexibility. 很大程度上,这个过程可以自动完成,但前提是您对该过程拥有足够的控制权。The process can be automated to a large extent, provided you are given sufficient control over the process. 例如,如果简单的二进制序列化不足,或者可能有特定原因决定需要对类中的哪些字段进行序列化,可能就会出现这种情况。For example, situations may arise where simple binary serialization is not sufficient, or there might be a specific reason to decide which fields in a class need to be serialized. 以下章节验证了随 .NET Framework 一起提供的可靠序列化机制,并强调了根据需要自定义该过程所能使用的一些重要功能。The following sections examine the robust serialization mechanism provided with .NET and highlight a number of important features that allow you to customize the process to meet your needs.

备注

如果使用不同的 .NET Framework 版本序列化和反序列化以 UTF-8 或 UTF-7 编码的对象,则不保留该对象的状态。The state of a UTF-8 or UTF-7 encoded object is not preserved if the object is serialized and deserialized using different .NET Framework versions.

警告

二进制序列化可能会十分危险。Binary serialization can be dangerous. 请不要从不受信任的源反序列化数据,也不要将序列化数据往返到不受控制的系统。Never deserialize data from an untrusted source and never round-trip serialized data to systems not under your control.

由于二进制序列化的性质允许在对象内修改私有成员,因此若要更改其状态,建议使用其他序列化框架,如在公共 API 曲面上操作的 JSON.NET。As the nature of binary serialization allows the modification of private members inside an object and therefore changing the state of it, other serialization frameworks like JSON.NET which operate on the public API surface are recommended.

.NET Core 中的二进制序列化Binary serialization in .NET Core

.NET Core 支持带有类型子集的二进制序列化。.NET Core supports binary serialization with a subset of types. 可在可序列化类型部分查看受支持的类型列表。You can see the list of supported types in the Serializable types section. 一组已定义的类型是完全可以在 .NET Framework 4.5.1 及更高版本之间和 .NET Core 2.0 及更高版本之间进行序列化的。The defined set of types are guaranteed to be serializable between .NET Framework 4.5.1 and later versions and .NET Core 2.0 and later versions. 其他 .NET 实现(如 Mono)并未正式得到支持,但应该也能使用。Other .NET implementations, such as Mono, aren't officially supported but should also be working.

可序列化类型Serializable types

本节内容In this section

参考Reference

  • System.Runtime.Serialization
    包含可用于序列化和反序列化对象的类。Contains classes that can be used for serializing and deserializing objects.