We want to persist the data, that is, to write data to a file, we can be in C # through the IO stream to operate, but also through serialization to operate, I am more recommended to use the serialization operation
Because if we want to persist an object to a file, if we use IO Stream file stream operation, we may not be able to implement it, but we can implement it easily with serialization, and when we get back to the data
Time, we get an object, but it's saved to a file that is a binary file
The specific implementation steps are as follows
First we have an entity object and this class is capable of supporting serialization operations, that is, mounting a [Serializable] tag
//indicates that the class can be serialized[Serializable] Public classPeoson {Private intAge ; Private stringname; Public intAge {Get{returnAge ;} Set{age =value;} } Public stringName {Get{returnname;} Set{name =value;} } PublicPeoson () {} PublicPeoson (stringNameintAge ) { This. Age =Age ; This. Name =name; } Public voidsay () {Console.WriteLine ("name: {0}, age {1}", Name,age); } }
We then prepare a collection in the main function and add data to it as a property of the collection, to serialize and deserialize the collection directly
Static voidMain (string[] args) { //Prepare set Merge to add data to itlist<peoson> list =NewList<peoson>(); Peoson P1=NewPeoson ("Xiao Huang", -); Peoson P2=NewPeoson ("Small white", -); Peoson P3=NewPeoson ("Xiao Qing", the); List. Add (p1); List. ADD (p2); List. ADD (p3); //Serialization ofSerializemethod (list); //deserializationList<peoson> list2= Reserializemethod ();//call the deserialized method whose method return value is a list collection foreach(Peoson IteminchLIST2)//iterating through the elements in the collection{Item.say (); } console.readkey (); } //Serialization Operations Public Static voidSerializemethod (list<peoson>list) { using(FileStream fs=NewFileStream ("Serialization. BTN", FileMode.Create)) {BinaryFormatter BF=NewBinaryFormatter (); Bf. Serialize (fs,list); Console.WriteLine ("serialization succeeds!"); } } //deserialization Operation Public StaticList<peoson>Reserializemethod () {using(FileStream fs=NewFileStream ("Serialization. BTN", FileMode.Open)) {BinaryFormatter BF=NewBinaryFormatter (); List<Peoson> list = (list<peoson>) BF. Deserialize (FS); returnlist; } } }
We've done the serialization and deserialization of the collection data.
How to implement serialization and deserialization in C #