C # serialization and deserialization,
Serialization and deserialization
This can directly convert the object to binary for storage and communication;
Add [Serializable] to the class to be serialized and use the BinaryFormatter class for operations;
Using System; using System. collections. generic; using System. linq; using System. text; using System. threading. tasks; using System. IO; using System. runtime. serialization. formatters. binary; namespace serialization and deserialization {class Program {static void Main (string [] args) {Student stu = new Student ("Liu Bei", 28, 'mal '); student stu2; string file = @ "E: \ code \ test \ test1.txt"; using (FileStream fsWriter = new FileStream (file, FileMode. openOrCreate, FileAccess. write) {// stu serialization; BinaryFormatter bf = new BinaryFormatter (); bf. serialize (fsWriter, stu);} using (FileStream fsReader = new FileStream (file, FileMode. open, FileAccess. read) {// The Reverse Sequence below; BinaryFormatter bf = new BinaryFormatter (); stu2 = (Student) bf. deserialize (fsReader);} Console. writeLine ("{0} {1} years old, is a {2} student", stu2.Name, stu2.Age, stu2.Gender); Console. readKey () ;}} [Serializable] public class Student {private string _ name; public string Name {get {return _ name ;}set {_ name = value ;}} private int _ age; public int Age {get {return _ age;} set {_ age = value ;}} private char _ gender; public char Gender {get {return _ gender;} set {_ gender = value ;}} public Student (string name, int age, char gender) {Name = name; age = age; Gender = gender ;}}}