157 recommendations for writing high-quality code to improve C # programs--Recommendation 56: More flexibility in controlling the serialization process with the inherited ISerializable interface

Source: Internet
Author: User
Tags ming

Recommendation 56: More flexibility in controlling the serialization process with the inherited ISerializable interface

The meaning of interface ISerializable is that if the feature serializable, and its like Ondeserializedattribute, Ondeserializingattribute, Onserializedattribute, Onserializingattribute, noserializable and so on can not fully meet the requirements of custom serialization, it is necessary to inherit the ISerializable.

The following is the workflow of the formatter: if the formatter discovers that the object inherits the ISerializable interface when serializing an object, it ignores all serialization attributes of the type. Instead of calling the type's GetObjectData method to construct a SerializationInfo object, it is internally responsible for adding all the fields that need to be serialized to the object (the word "add" may not be appropriate because we can dispose of the field arbitrarily before adding it). In the example of recommendation 55, if you want to construct a corresponding value for chinesename, you should do so if the class inherits the ISerializable interface:

    classProgram {Static voidMain () {person liming=NewPerson () {FirstName ="Ming", LastName ="Li" }; Binaryserializer.serializetofile (liming,@"C +","Person.txt"); Person P= Binaryserializer.deserializefromfile<person> (@"C:\person.txt");            Console.WriteLine (P.firstname);            Console.WriteLine (P.lastname);                   Console.WriteLine (P.chinesename); }} [Serializable] Public classperson:iserializable { Public stringFirstName;  Public stringLastName;  Public stringChinesename;  PublicPerson () {}protectedPerson (SerializationInfo info, StreamingContext context) {FirstName= info. GetString ("FirstName"); LastName= info. GetString ("LastName"); Chinesename=string. Format ("{0} {1}", LastName, FirstName); }        voidISerializable.GetObjectData (SerializationInfo info, StreamingContext context) {info. AddValue ("FirstName", FirstName); Info. AddValue ("LastName", LastName); }    }

Serialization Tool Class:

     Public classBinaryserializer {//serializing a type to a string         Public Static stringSerialize<t>(T t) {using(MemoryStream stream =NewMemoryStream ()) {BinaryFormatter Formatter=NewBinaryFormatter (); Formatter.                Serialize (stream, T); returnSystem.Text.Encoding.UTF8.GetString (stream.            ToArray ()); }        }        //serializing a type to a file         Public Static voidSerializetofile<t> (T T,stringPathstringfullName) {            if(!directory.exists (path))            {directory.createdirectory (path); }            stringFullPath =Path.Combine (Path, fullName); using(FileStream stream =NewFileStream (FullPath, FileMode.OpenOrCreate)) {BinaryFormatter Formatter=NewBinaryFormatter (); Formatter.                Serialize (stream, T); Stream.            Flush (); }        }        //deserializing a string into a type         Public StaticTResult deserialize<tresult> (stringSwhereTResult:class        {            byte[] bs =System.Text.Encoding.UTF8.GetBytes (s); using(MemoryStream stream =NewMemoryStream (BS)) {BinaryFormatter Formatter=NewBinaryFormatter (); returnFormatter. Deserialize (Stream) asTResult; }        }        //deserializing a file into a type         Public StaticTResult deserializefromfile<tresult> (stringPathwhereTResult:class        {            using(FileStream stream =NewFileStream (path, FileMode.Open)) {BinaryFormatter Formatter=NewBinaryFormatter (); returnFormatter. Deserialize (Stream) asTResult; }        }    }
View Code

We handle serialization in method GetObjectData and then process deserialization in a constructed method with parameters. Although there is no place in the interface to point out the need for such a constructor, this is really needed unless we are not going to deserialize it back after serialization.

This example does not show the advantages of the ISerializable interface over the serializable feature, as shown in the following example:

Serializes a person and then converts it to another object in deserialization: the Personanother type Object. To achieve this function, the person and personanother are required to implement the ISerializable interface, the original is very simple, is in the person class of the GetObjectData method of processing serialization, Deserialized in the protected construction method of the Personanother.

    classProgram {Static voidMain () {person liming=NewPerson () {FirstName ="Ming", LastName ="Li" }; Binaryserializer.serializetofile (Liming,@"C +","Person.txt"); Personanother P= Binaryserializer.deserializefromfile<personanother> (@"C:\person.txt");        Console.WriteLine (P.name); }} [Serializable]classpersonanother:iserializable { Public stringName {Get;Set; } protectedPersonanother (SerializationInfo info, StreamingContext context) {Name= info. GetString ("Name"); }        voidISerializable.GetObjectData (SerializationInfo info, StreamingContext context) {}} [Serializable] Public classperson:iserializable { Public stringFirstName;  Public stringLastName;  Public stringChinesename;  PublicPerson () {}protectedPerson (SerializationInfo info, StreamingContext context) {}voidISerializable.GetObjectData (SerializationInfo info, StreamingContext context) { info. SetType ( typeof (Personanother)); Info. AddValue ("Name",string. Format ("{0} {1}", LastName, FirstName)); }    }

In the GetObjectData method of the person type, it is important to have a code:

Info. SetType (typeof(Personanother));

It is responsible for telling the serializer that I want to be deserialized into personanother. The type Personanother is simple, and it doesn't even need to know who will be deserialized into it, and it doesn't need to do any special processing.

ISerializable interface This feature is very important, if used properly, in the version upgrade, it can handle the problem of the type because of the changes in the field.

Turn from: 157 recommendations for writing high-quality code to improve C # programs Minjia

157 recommendations for writing high-quality code to improve C # programs--Recommendation 56: More flexibility in controlling the serialization process with the inherited ISerializable interface

Related Article

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.