157 recommendations for writing high-quality code to improve C # programs--Recommendation 55: Reduce serializable fields with custom features

Source: Internet
Author: User

Recommendation 55: Reduce serializable fields with custom features

An attribute (attribute) can declaratively add a comment to a target element in your code. The runtime can achieve the purpose of changing the runtime behavior of the target element by querying the metadata information in these managed blocks. There are 4 such features under the System.Runtime.Serialization namespace:

    • Ondeserializedattribute, when applied to a method, specifies that the method is called immediately after the object is deserialized.
    • Ondeserializingattribute, when applied to a method, specifies that this method is called when deserializing an object.
    • Onserializedattribute, when applied to a method, specifies that the method is called immediately after the object is serialized.
    • Onserializingattribute, when applied to a method, specifies that this method is called when serializing an object.

These features allow for more flexibility in handling serialization and deserialization. For example, we can take advantage of this to further reduce some serializable fields.

The person class consists of Chinesename, FirstName, LastName fields:

    [Serializable]    class  person    {        publicstring   FirstName;          Public string LastName;          Public string chinesename;    }

We know that chinesename can actually be inferred from FirstName and LastName, so this means that chinesename does not need to be serialized. At this point, we can use the feature to provide a way to calculate the value of the Chinesename after serialization is complete:

    classProgram {Static voidMain () {person liming =NewPerson () {FirstName ="Ming", LastName ="Li", Chinesename ="Li Ming" }; Binaryserializer.serializetofile (liming,@"C +","Person.txt"); Person Person= Binaryserializer.deserializefromfile<person> (@"C:\Person.txt"); Console.WriteLine (person.        Chinesename); }} [Serializable]classPerson { Public stringFirstName;  Public stringLastName; [NonSerialized] Public stringChinesename; [Ondeserializedattribute]voidonserialized (StreamingContext context) {Chinesename=string. Format ("{0} {1}", LastName, FirstName); }    }

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; }        }    }

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 55: Reduce serializable fields with custom features

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.