一、 什麼是序列化對象?
序列化是將對象狀態轉換為可保持或傳輸的格式的過程。
在序列化期間,對象將其目前狀態寫入到臨時或持久性儲存區。以後,可以通過從儲存區中讀取或還原序列化對象的狀態,重新建立該對象。與序列化相對的是還原序列化,它將流轉換為對象。這兩個過程結合起來,就使得資料能夠被輕鬆地儲存和傳輸。
確切的說應該是對象的序列化,一般程式在運行時,產生對象,這些對象隨著程式的停止運行而消失,但如果我們想把某些對象(因為是對象,所以有各自不同的特性)儲存下來,在程式終止運行後,這些對象仍然存在,可以在程式再次運行時讀取這些對象的值,或者在其他程式中利用這些儲存下來的對象。這種情況下就要用到對象的序列化。
System.Runtime.Serialization和System.Runtime.Serialization.Formatters命名空間中提供了序列化對象的基礎架構。這兩個類實現了基礎架構。
二、 Framework中有兩個可用的實現方式:
System.Runtime.Serialization.Formatters.Binary:這個命名空間也包含了BinaryFormatter類,它能把對象序列化為二進制數據,把二進制數據序列化為對象。
System.Runtime.Serialization.Formatters.Soap:這個命名空間包含了SoapFormatter類中,它能把對象序列化為SOAP格式的XML數據,把SOAP格式的XML數據序列為對象。
三、例子:
1、新增一個Windows應用程式,其中Form1有兩個TextBox控制項
註:txb:用於顯示傳入值後,Product類產生的結果
txbResult:用於顯示還原序列化後的結果
2、增加一個Product類,主要作用是對傳入值格式化
3、在應用程式中對Product類產生的結果進行序列化
代碼:
Product類的代碼:namespace SerializerFile
{
/// <summary>
/// 此類用作對值入值格式化
/// Serializable:作此標記後方可序列化
/// </summary>
[Serializable]
class Product
{
public long lId;
public string sName;
public double dPrice;
/// <summary>
/// 加上此標記無法序列化
/// </summary>
[NonSerialized]
string sNotes;
public Product(long alId, string asName, double adPrice, string asNotes)
{
lId = alId;
sName = asName;
dPrice = adPrice;
sNotes = asNotes;
}
public override string ToString()
{
//格式化傳入的值
return string.Format("{0}:{1} (${2:F2}) {3}", lId, sName, dPrice, sNotes);
}
}
}
Form1中的代碼:
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
namespace SerializerFile
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
//調用序列化方法
SerializationClass();
}
/// <summary>
/// 序列化方法
/// </summary>
private void SerializationClass()
{
List<Product> products = new List<Product>();
//產生值
products.Add(new Product(1, "Spiky Pung", 1000.00, "Good stuff."));
products.Add(new Product(2, "Gloop Galloop Soup", 25.0, "Tasty."));
products.Add(new Product(4, "Hat Sauce", 12.0, "One for the kids."));
//為了方便,在介面中顯示產生的值
foreach (Product pProduct in products)
{
txb.Text += pProduct.ToString()+"\b\r";
}
//定義可序列化介面
IFormatter ifSerializer = new BinaryFormatter();
FileStream fsSaveFile = new FileStream(@"D:\Products.bin",FileMode.Create,FileAccess.Write);
//序列化(將products中的內容序化到檔案D:\Products.bin)
ifSerializer.Serialize(fsSaveFile,products);
fsSaveFile.Close();
FileStream fdLoadFile = new FileStream(@"D:\Products.bin", FileMode.Open, FileAccess.Read);
//還原序列化
List<Product> lSaveProducts = ifSerializer.Deserialize(fdLoadFile) as List<Product>;
fdLoadFile.Close();
//在介面中顯示還原序列化後的結果
foreach (Product pProduct in lSaveProducts)
{
txbResult.Text += pProduct.ToString()+"\b\r";
}
}
}
}
結果顯示如下: