很久以前看書有看到,都一直沒有機會實做
剛好最近比較閒就寫來玩玩
序列化是將物件儲存到binary的技術
很久以前看書有看到,都一直沒有機會實做
剛好最近比較閒就寫來玩玩
序列化是將物件儲存到binary的技術
可以先將物件中的所有資訊存到binary檔案中
下次要用的時候在Deserialize拿出來就好了
要可以被序列化的物件必須要幫物件加上Serializable屬性
不然隨便序列化物件會收到錯誤訊息
所以物件要這樣寫
[Serializable]
public class Member {
private string _name;
private int _age;
public string Name {
get { return _name; }
}
最上面加上Serializable就OK了
再來就寫一個簡單的範例序列化Menber這個物件吧:
首先引用System.Runtime.Serialization.Formatters.Binary這個Namespace
using System.Runtime.Serialization.Formatters.Binary;
然後cloudio寫了一個小小的function
private static void Serialize(string FileName, object serializeObject) {
using (System.IO.Stream output = new System.IO.FileStream(FileName, System.IO.FileMode.Create)) {
BinaryFormatter binFormat = new BinaryFormatter();
binFormat.Serialize(output, serializeObject);
}
}
在準備一下要序列化的物件
[Serializable]
public class Member {
private string _name;
private int _age;
public string Name {
get { return _name; }
}
public int Age {
get { return _age; }
}
public Member(string name, int age) {
this._name = name;
this._age = age;
}
public Member() {
this._name = "cloudio";
this._age = 17;
}
}
就可以開始玩了
這邊只要這樣下一段code
string datFileName = @"C:\test.dat";
Serialize(datFileName, new Member("Cloudio", 27));
就可以看到C:\test.dat這個檔案了
反序列化就這樣的話一樣準備一個function
private static object Deserialize(string FileName) {
using (System.IO.Stream output = System.IO.File.OpenRead(FileName)) {
BinaryFormatter binFormat = new BinaryFormatter();
return binFormat.Deserialize(output);
}
}
這樣呼叫:
string datFileName = @"C:\test.dat";
Member tmpdat = (Member)Deserialize(datFileName);
Console.WriteLine(tmpdat.Name);
順便輸出看看是不是剛剛被序列化的那個物件:)
那序列化成xml呢?
要準備System.Xml.Serialization這個NameSpace
這邊就直接寫兩個function來處理了:
private static void XmlSerializer<T>(string FileName, T SerializerObject) {
using (System.IO.Stream output = new System.IO.FileStream(FileName, System.IO.FileMode.Create)) {
System.Xml.Serialization.XmlSerializer xmlSerializer = new System.Xml.Serialization.XmlSerializer(typeof(T));
xmlSerializer.Serialize(output, SerializerObject);
}
}
private static T XmlDeserialize<T>(string FileName) {
using (System.IO.Stream output = System.IO.File.OpenRead(FileName)) {
System.Xml.Serialization.XmlSerializer xmlSerializer = new System.Xml.Serialization.XmlSerializer(typeof(T));
return (T)xmlSerializer.Deserialize(output);
}
}
一樣寫code來測試:
string xmlFileName = @"C:\test.xml";
XmlSerializer<Member>(xmlFileName, new Member());
Member tmpXml = XmlDeserialize<Member>(xmlFileName);
Console.WriteLine(tmpXml.Name);
因為xml的序列化要求物件必須要有一個不用傳入參數的建構函式
所以cloudio在物件上才會做兩個建構函式...
有錯誤歡迎您的訂正 謝謝:)