How to Implement serialization and deserialization in C,
If we want to perform a persistent operation on the data, that is, writing the data to a file, we can operate it through the IO stream in C #, or through serialization, serialization is recommended for me.
Because if we want to persist an object to a file, we may not be able to implement it if we use the IO stream file stream operation, but we can implement it easily with serialization, and when we get the data back
We also get an object, but it is saved to a binary file.
The specific implementation steps are as follows:
First, we have an object and this class supports serialization, that is, mounting with the [Serializable] Mark.
// This class can be serialized [Serializable] public class Peoson {private int age; private string name; public int Age {get {return age;} set {age = value ;}} public string Name {get {return name;} set {name = value;} public Peoson () {} public Peoson (string name, int age) {this. age = age; this. name = name;} public void say () {Console. writeLine ("name: {0}, age {1}", name, age );}}
Then we prepare a set in the Main function, and use the class created above as the set attribute to add data to it, and directly perform serialization and deserialization operations on the set.
Static void Main (string [] args) {// prepare a set and add it to the data List <Peoson> list = new List <Peoson> (); peoson p1 = new Peoson ("Xiao Huang", 18); Peoson p2 = new Peoson ("Xiao Bai", 28); Peoson p3 = new Peoson ("Xiao Qing", 15 ); list. add (p1); list. add (p2); list. add (p3); // SerializeMethod (list); // deserialization List <Peoson> list2 = ReserializeMethod (); // call the deserialization method. Its return value is a List set foreach (Peoson item in list2) // traverses the element {item. say ();} Console. ReadKey ();} // serialization Operation public static void SerializeMethod (List <Peoson> list) {using (FileStream fs = new FileStream ("serialization. btn ", FileMode. create) {BinaryFormatter bf = new BinaryFormatter (); bf. serialize (fs, list); Console. writeLine ("serialization successful! ") ;}// Deserialization Operation public static List <Peoson> ReserializeMethod () {using (FileStream fs = new FileStream (" serialization. btn ", FileMode. open) {BinaryFormatter bf = new BinaryFormatter (); List <Peoson> list = (List <Peoson>) bf. deserialize (fs); return list ;}}}
Now we have serialized and deserialized the set data.