- 帖子
- 26
- 主題
- 2
- 精華
- 0
- 積分
- 52
- 點名
- 0
- 作業系統
- Mac OS X
- 軟體版本
- Office 2010
- 閱讀權限
- 20
- 性別
- 男
- 註冊時間
- 2010-8-13
- 最後登錄
- 2010-10-29
|
C#的物件序列化可將執行時期的物件狀態輸出至stream。本文介紹使用BinaryFormatter的方法。
使用BinaryFormatter需引用下列命名空間:
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
要保存狀態的類別定義需要標記[Serializable]屬性,例如一個簡單的類別宣告如下:
[Serializable]
class MyContact
{
public string name;
public int age;
public MyContact(string name, int age)
{
this.name = name;
this.age = age;
}
}
將執行個體的狀態保存成檔案:
MyContact data = new MyContact("John", 14);
IFormatter fmt = new BinaryFormatter();
Stream ostream = new FileStream("MyData.binary", FileMode.Create, FileAccess.Write, FileShare.None);
fmt.Serialize(ostream, data);
ostream.Close();
這邊使用了FileStream(引用System.IO)。
方法同樣適用於Stream的衍生類別。 |
|