157 recommendations for writing high-quality code to improve C # programs-Recommendation 57: Implementing ISerializable subtypes should be responsible for the serialization of the parent class

Source: Internet
Author: User

Recommendation 57: Implementing the ISerializable subtype should be responsible for the serialization of the parent class

We are going to implement the type of inherit from ISerializable employee has a parent class person, assuming that the person does not implement serialization, but now the subclass employee needs to satisfy the serialized scene. However, the serializer does not handle the person type object by default, and these things can only be done by ourselves.

The following is an inappropriate implementation where the serializer only discovers and processes the salary field in the employee:

    classProgram {Static voidMain () {Employee liming=NewEmployee () {Name ="liming", Salary = - }; Binaryserializer.serializetofile (Liming,@"C +","Person.txt"); Employee limingcopy= Binaryserializer.deserializefromfile<employee> (@"C:\person.txt"); Console.WriteLine (string. Format ("name: {0}", Limingcopy.name)); Console.WriteLine (string. Format ("salary: {0}", limingcopy.salary)); }    }         Public classPerson { Public stringName {Get;Set; } } [Serializable] Public classEmployee:person, ISerializable { Public intSalary {Get;Set; }  PublicEmployee () {}protectedEmployee (SerializationInfo info, StreamingContext context) {Salary= info. GetInt32 ("Salary"); }         Public Override voidGetObjectData (SerializationInfo info, StreamingContext context) {info. AddValue ("Salary", Salary); }    }    

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

The output is:

Name:
Salary: 2000

See, the Name field is not handled correctly. This requires us to modify the GetObjectData method of the protected constructor method in type employee, and for it to join the processing of the parent class field:

[Serializable] Public classEmployee:person, ISerializable { Public intSalary {Get;Set; }  PublicEmployee () {}protectedEmployee (SerializationInfo info, StreamingContext context) {Name= info. GetString ("Name"); Salary= info. GetInt32 ("Salary"); }         Public voidGetObjectData (SerializationInfo info, StreamingContext context) {info. AddValue ("Name", Name); Info. AddValue ("Salary", Salary); }    } 

Modified output:

Name: Liming
Salary: 2000

In the above example, the person class is not set to support serialization. Now, assuming that the person class has implemented the ISerializable interface, the problem is relatively easy to handle, and in the subclass of employee, we only need to call the parent class's protected constructor and GetObjectData method. As shown below:

[Serializable] Public classperson:iserializable { Public stringName {Get;Set; }  PublicPerson () {}protectedPerson (SerializationInfo info, StreamingContext context) {Name= info. GetString ("Name"); }         Public Virtual voidGetObjectData (SerializationInfo info, StreamingContext context) {info. AddValue ("Name", Name); }} [Serializable] Public classEmployee:person, ISerializable { Public intSalary {Get;Set; }  PublicEmployee () {}protectedEmployee (SerializationInfo info, StreamingContext context):Base(info, context) {Salary= info. GetInt32 ("Salary"); }         Public Override voidGetObjectData (SerializationInfo info, StreamingContext context) {Base.            GetObjectData (info, context); Info. AddValue ("Salary", Salary); }    }

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 57: Implementing ISerializable subtypes should be responsible for the serialization of the parent class

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.