有時,您會發現需要儲存組件的狀態。例如,可以這樣做以儲存有關組件使用者的個人資訊,或者更改自訂控制項的預設配置。
可以通過一個稱為“序列化”的過程將組件的狀態儲存到檔案中。序列化允許將對象轉換成資料流,然後可以將資料流儲存到檔案中。資料流可以通過還原序列化再轉換成對象。
.NET Framework 為序列化提供了兩個格式化程式:BinaryFormatter 類和 SoapFormatter 類。這些類通過通常在記憶體中的“對象圖”(對象在記憶體中的表示形式)並將其轉換成資料流。正如它們各自的名稱所表示的,BinaryFormatter 將對象圖轉換成二進位流(對傳統型應用程式最有用),而 SOAPFormatter 將對象圖轉換成簡易物件存取通訊協定 (SOAP) (SOAP) 格式(對 Internet 應用程式最有用)。這些流然後儲存為檔案,在需要時可以還原序列化和轉換回對象。
序列化流
儲存組件狀態
- 對要序列化的組件應用 SerializableAttribute 特性。
[Serializable()]public class Account{ // ' Insert code to implement class.}
- 建立該類的一個執行個體作為要儲存的對象。
Account myAccount = new Account();
- 建立一個 Stream 對象作為將為序列化資料提供儲存庫的檔案。
using System.IO;// This creates a new file with the name SavedAccount.txt, and creates // a Stream object to write data to that file. The GetFolderPath method // is used to get the path to the current user's Personal folder.Stream myFileStream = File.Create (System.Environment.GetFolderPath (System.Environment.SpecialFolder.Personal));
- 建立一個格式化程式類執行個體。
- 如果要將對象圖轉換成二進位流,建立一個 BinaryFormatter 類執行個體。
using System.Runtime.Serialization.Formatters.Binary;BinaryFormatter serializer = new BinaryFormatter();
- 如果要將對象圖轉換成 SOAP 流,建立一個 SoapFormatter 類執行個體。
注意 項目中必須有對
System.Runtime.Serialization.Formatters.Soap 命名空間的引用。
using System.Runtime.Serialization.Formatters.Soap;SoapFormatter serializer = new SoapFormatter();
- 調用格式化程式的 Serialize 方法,將對象寫入 Stream。
serializer.Serialize(myFileStream, myAccount);myFileStream.Close();
- 關閉檔案流以完成序列化。
現在 SavedAccount.txt 檔案中有一個以二進位格式儲存的對象執行個體。
還原序列化流
儲存了對象後,有時需要檢索它。可以用序列化組件時使用的同一格式化程式來還原序列化組件。
還原儲存的組件
- 將同一類型的某個變數聲明為要還原的類。
Account restoredAccount;
- 建立一個 Stream 對象並開啟包含序列化對象的檔案。
using System.IO;Stream myFileStream = File.OpenRead (System.Environment.GetFolderPath (System.Environment.SpecialFolder.Personal));
- 建立一個與序列化資料時使用的格式化程式類具有相同類型的執行個體。
- 下面的樣本顯示如何使用 BinaryFormatter 類。
using System.Runtime.Serialization.Formatters.Binary;BinaryFormatter deserializer = new BinaryFormatter();
- 下面的樣本顯示如何使用 SoapFormatter 類。
注意 項目中必須已有對
System.Runtime.Serialization.Formatters.Soap 命名空間的引用。
using System.Runtime.Serialization.Formatters.Soap;SoapFormatter deserializer = new SoapFormatter();
- 調用格式化程式的 Deserialize 方法將檔案流轉換成一個對象圖,並通過顯式類型轉換將該對象圖轉換成所需類型的對象。
// The explicit cast converts the file stream to an object of the type // specified. If the object in the file stream cannot be converted to // the specified type, an error will result.restoredAccount = (Account)(deserializer.Deserialize(myFileStream));myFileStream.Close();
安全記事 不應使用此技術來儲存任何敏感性資料或保密資料,因為這不是確保資料安全的可接受方式。有關為資料建立安全加密方案的資訊,請參見 System.Security.Cryptography 命名空間。
本文來自MSDN:MSDN Home > Visual Studio .NET > Visual Basic 和 Visual C# > 使用組件編程 > 組件創作 > 在組件中實現屬性、方法、成員和事件