Hey, learn to serialize

Source: Internet
Author: User

Hey, no matter what happens, the school does not have a teacher class, we have to take the initiative to learn, learning is not to fall, although we have no teacher to teach us this week, but we have to study, but also remember the previous few days, always simple to say the next serialization, That time is just a simple listen to the content, only know the need for a keyword, today there is no class there is no new knowledge summary, then I would like to find something I want to know, the following detailed summary of serialization and deserialization.

I. Serialization

Serialization: Yes The process of transforming the state information of an object into a form that can be stored or transmitted. During serialization, an object writes its current state to a temporary or persistent store. Later, the object can be recreated by reading or deserializing the state of the object from the store.

Serialization of applications: persist objects to storage, disks, databases, copy objects to the Clipboard, transfer objects over the network, and back up objects (deep copy). )

Serialized namespaces: Using System.Runtime.Serialization.Formatters.Binary;

Here's a simple example of using list generics:

list<int> list =Newlist<int> ();//List genericsList. ADD (1); List. ADD (2); List. ADD (3); using(FileStream fs =NewFileStream ("Data.txt", FileMode.Create))//When creating file time using create{BinaryFormatter BF=NewBinaryFormatter (); Bf.   Serialize (FS, list); //here is the method of serialization, transforming the object into a binary form saved in a file by a stream}

Here we use list<int> to create a serialization, and here's why we can serialize that, mainly because the list is a serializable class, and what is the identity of the serializable class? is to add a [Serializable] to the front of the class, we write a deserialization pattern, and of course, deserialization is created in the case of serialization, so you need to be careful here.
if(File.exists ("Data.txt"))//when the deserialization time first determines whether the file exists                using(FileStream fs =NewFileStream ("Data.txt", FileMode.Open)) {BinaryFormatter BF=NewBinaryFormatter (); List<int> list = bf. Deserialize (FS) aslist<int>; //It is important to note here that what type we serialize into is what type we are going back to, and the BF. The deserialize (FS) returned is an object type, so the conversion to the list<int> type//deserializes the contents of a stream into objects through a stream-read file                     for(inti =0; I < list. Count; i++) {Console.WriteLine (list[i]); //iterate through each item                    }                }

here is the creation of our deserialization, we can see the first line of code above, here we should be aware of, before deserialization, it is important to determine whether our serialized file exists, in the case of the existence, we can deserialize, our serialization time using the method is Serialize, It is very important that the deserialize method is called at deserialization time, and that we have to pay attention to the type conversion in deserialization time.

The following is a definition of a class, you can have inheritance in this class, and then let it serialization and deserialization.

first define a student class, define a person class with the dog class, the person is the parent class, student is a subclass, inherit the parent class person class, and the dog is just a property of student, let it serialize and deserialize a bit.

[Serializable]     class person                                  {        privateint age ;          Public int Age        {            getreturn age ;}             Set {age = value;}        }    }
[Serializable]classStudent:P Erson {Private stringname;  Public stringName {Get{returnname;} Set{name =value;} }        PrivateDog Dog; InternalDog Dog {Get{returnDog;} Set{dog =value;} }         Public voidSayhi () {Console.WriteLine ( This. Name); }    }
[Serializable]     class Dog    {        privatestring  name;          Public string Name        {            getreturn  name;}             Set {name = value;}     }}}

The above is the definition of the three classes, the implementation of the inheritance method, it is important to note here: Serialization is not inherited through inheritance, so when either the student class or the person of any class to serialize, then they are serialized, The attribute classes in student must also be serializable here, where error-prone, we need to pay more attention.

Here's how to implement serialization and deserialization,

 #regionCustomizing a Serializable classStudent S=NewStudent (); S.name="Zhangsan"; S.dog=NewDog ();//here is the definition of a dog class, and the dog class as one of the attributes of studentS.dog.name ="Xiaogou"; using(FileStream fs =NewFileStream ("a.txt", FileMode.Create)) {BinaryFormatter BF=NewBinaryFormatter (); Bf.            Serialize (FS, s); }            #endregion
 #regionCustom deserializationif(File.exists ("a.txt"))            {                using(FileStream fs =NewFileStream ("a.txt", FileMode.Open)) {BinaryFormatter BF=NewBinaryFormatter (); Student s= BF. Deserialize (FS) asStudent; S.dog.name="Xiaogou";                    S.sayhi ();                 Console.WriteLine (S.dog.name); }            }            #endregion

In contrast, one is a system-defined list class, one that is our own definition of serializable person,student and student, and the way they implement serialization is to add a serializable identity, that's all, We must be aware of the need to add an identity when implementing serialization, and then implement serialization and deserialization.

Hey, I finally know. Serialization and deserialization, although only to know, but still very happy, it is said that the serialization is rare ah, but this is still a simple preliminary understanding, I will continue to learn this, hey, try.

Hey, learn to serialize

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.