Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Phân giải đối tượng (Object Serialization) trong C#

Để phân giải đối tượng, bạn sử dụng phương thức BinaryFormatter.Serialize(stream, reference).

Định nghĩa constructor cho lớp Employee:

public Employee(int id, string name, int salary) {
    this.id = id;
    this.name = name;
    this.salary = salary;
}

Thiết lập luồng file và đối tượng BinaryFormatter:

FileStream fStream = new FileStream("d:\\new.txt", FileMode.OpenOrCreate);
BinaryFormatter bFormat = new BinaryFormatter();

Tạo đối tượng Employee và phân giải:

Employee emp = new Employee(001, "Jim", 30000);
bFormat.Serialize(fStream, emp);