CÁC GIẢI PHÁP LẬP TRÌNH C# - Trang 613

613

Chương 16: Các giao diện và mẫu thông dụng

if ((con.State & StreamingContextStates.File) == 0) {

inf.AddValue("Address", address);

}

}

// Chép đè Object.ToString để trả về chuỗi mô tả Employee.

public override string ToString() {

StringBuilder str = new StringBuilder();

str.AppendFormat("Name: {0}\n\r", Name);

str.AppendFormat("Age: {0}\n\r", Age);

str.AppendFormat("Address: {0}\n\r", Address);

return str.ToString();

}

public static void Main(string[] args) {

// Tạo một đối tượng Employee mô tả Phuong.

Employee phuong = new Employee("Phuong", 23, "HCM");

// Hiển thị Phuong.

Console.WriteLine(phuong);

// Tuần tự hóa Phuong với đích là một miền ứng dụng khác.

// Địa chỉ của Phuong sẽ được tuần tự hóa.

Stream str = File.Create("phuong.bin");

BinaryFormatter bf = new BinaryFormatter();

bf.Context =

new StreamingContext(StreamingContextStates.CrossAppDomain);

bf.Serialize(str, phuong);

str.Close();

// Giải tuần tự hóa và hiển thị Phuong.

str = File.OpenRead("phuong.bin");