二進位序列化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 所提供的穩固序列化機制,並強調數種能讓您自訂程序以滿足需求的重要功能。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.