83
Chương 2: Thao tác dữ liệu
people.Add("Phong");
people.Add("Nam");
// Tuần tự hóa đối tượng ArrayList.
FileStream str = File.Create("people.bin");
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(str, people);
str.Close();
// Giải tuần tự hóa đối tượng ArrayList.
str = File.OpenRead("people.bin");
bf = new BinaryFormatter();
people = (ArrayList)bf.Deserialize(str);
str.Close();
// Hiển thị nội dung của đối tượng ArrayList
// đã-được-giải-tuần-tự-hóa.
foreach (string s in people) {
System.Console.WriteLine(s);
}
}
}
Bạn có thể sử dụng lớp
SoapFormatter
theo cách như được trình bày trong lớp
BinarySerializationExample
ở trên, chỉ cần thay mỗi thể hiện của lớp
BinaryFormatter
bằng
thể hiện của lớp
SoapFormatter
và thay đổi chỉ thị
using
để nhập không gian tên
System.Runtime.Serialization.Formatters.Soap
. Ngoài ra, bạn cần thêm một tham chiếu
đến
System.Runtime.Serialization.Formatters.Soap.dll
khi biên dịch mã. File
SoapSerializationExample.cs trong đĩa CD đính kèm sẽ trình bày cách sử dụng lớp
SoapFormatter
.
Hình 2.1 và 2.2 dưới đây minh họa hai kết quả khác nhau khi sử dụng lớp
BinaryFormatter
và
SoapFormatter
. Hình 2.1 trình bày nội dung của file people.bin được tạo ra khi sử dụng
BinaryFormatter
, hình 2.2 trình bày nội dung của file people.xml được tạo ra khi sử dụng
SoapFormatter
.