保存於XML中的序列化C#類
先聲明那個需要保存的類如下:
1 [Serializable]
2 public class HalfHour
3 {
4 public string ibtnHalfHourName;
5 public int status;
6 public bool isFirst;
7 public int eventID;
8 public bool isHead;
9
10 public HalfHour()
11 {
12 this.ibtnHalfHourName = "";
13 this.status = HalfHour.BLANK;
14 this.isFirst = false;
15 this.eventID = -1;
16 this.isHead = false;
17 }
18
19 }
然後為這個類分別定義一個Serial和Deserial兩個方法,分別完成序列化和反序列化這兩件事(必要的namespace是System.XML.Serialization和System.IO):
1 public static void Serial(HalfHour[] halfHours, string path)
2 {
3 XmlSerializer xmlSerializer = new XMLSerializer(typeof(HalfHour[]));
4 TextWriter writer = new StreamWriter(path);
5 try
6 {
7 XMLSerializer.Serialize(writer, halfHours);
8 }
9 finally
10 {
11 writer.Close();
12 }
13 }
14
15 public static HalfHour[] Deserial(string path)
16 {
17 XmlSerializer xmlSerializer = new XMLSerializer(typeof(HalfHour[]));
18 FileStream fs = new FileStream(path, FileMode.Open);
19 HalfHour[] halfHours;
20 try
21 {
22 halfHours = (HalfHour[])XMLSerializer.Deserialize(fs);
23 }
24 finally
25 {
26 fs.Close();
27 }
28 return halfHours;
29 }
這兩個函數的調用應該很容易理解:對於Serial,你只需提供XML的保存路徑和你需要序列化的那個類數組。而Deserial則只需要提供讀取的XML路徑即可。
保存於隱藏表單中的序列化C#類
要序列化的類的聲明和上面一致,這裡不再重復。但你需要在你的Web頁面中定義你的隱藏表單。
下面是Serial和Deserial函數的重載版本,這裡要引入System.Text的namespace:
1 public static string Serial(HalfHour[] halfHours)
2 {
3 XmlSerializer xmlSerializer = new XMLSerializer(typeof(HalfHour[]));
4 MemoryStream memoryStream = new MemoryStream();
5 XMLSerializer.Serialize(memoryStream, halfHours);
6 return Encoding.UTF8.GetString(memoryStream.GetBuffer());
7 }
8
9 public static HalfHour[] Deserial(string serialedObject)
10 {
11 XmlSerializer xmlSerializer = new XMLSerializer(typeof(HalfHour[]));
12 MemoryStream memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(serialedObject));
13 return (HalfHour[])XMLSerializer.Deserialize(memoryStream);
14 }
兩種方式的比較
選擇文件讀寫方式顯然在服務器運行速度上會比較慢,而且要構思不產生沖突的文件名,同時還要考慮文件系統的讀寫權限問題。寫入表單則沒有這個問題,但是如果序列化的對象過大的話,會是整個頁面文件變得很大,造成傳輸過程的緩慢。所以建議如果要序列化的對象較小,則選擇後者。反之則選擇前者。