C # Serialization Understanding 2 (RPM)

Source: Internet
Author: User
Tags object serialization

I. Overview

Serialization is the transformation of an object into a stream. The reverse process is deserialization.

What are the occasions where this technology is used?

1. Save the object locally and restore the object the next time you run the program.

2. Transfer the object to another terminal on the network, and then restore the object at this terminal.

3. Copy the system's sticky board, then use the shortcut key Ctrl + V to restore the object.

The commonly used serialized stream has binary (binary stream), Xml,soap.

Ii. examples of serialization and deserialization use:

Here we present the serialization and deserialization in the form of a functional class:

 public class Serializer {//serializes the type to a string public static string serialize<t> (T t) where t:class  {using (MemoryStream stream=new MemoryStream ()) {BinaryFormatter formatter = new                BinaryFormatter (); Formatter.                Serialize (stream, T); Return System.Text.Encoding.UTF8.GetString (stream.            ToArray ()); }}//Serialize the type to file public static void Serializetofile<t> (T T, string path, String fullName) where T:class {if (!            Directory.Exists (Path)) {directory.createdirectory (path); } string FullPath = String.            Format (@ "{0}\{1}", Path, fullName); using (FileStream stream = new FileStream (fullpath,filemode.openorcreate)) {BinaryFormatter for                matter = new BinaryFormatter (); Formatter.                Serialize (stream, T); Stream.            Flush (); }        }        //Serializes the type to file public static void Serializetofilebyxml<t> (T T, string path, String fullName) where T:class {if (!            Directory.Exists (Path)) {directory.createdirectory (path); } string FullPath = String.            Format (@ "{0}\{1}", Path, fullName); using (FileStream stream = new FileStream (FullPath, FileMode.OpenOrCreate)) {XmlSerializer form                Atter = new XmlSerializer (typeof (T)); Formatter.                Serialize (stream, T); Stream.            Flush ();        }}//deserialize string to type public static TResult deserialize<tresult> (string s) where Tresult:class            {byte[] bs = System.Text.Encoding.UTF8.GetBytes (s); using (MemoryStream stream = new MemoryStream (BS)) {BinaryFormatter formatter = new Binaryforma                Tter (); Return formatter.            Deserialize (stream) as TResult;        }}//Deserializes the file into a type public static TResult deserializefromfile<tresult> (string path) where Tresult:class {using (FileStream stream = new FileStream (Path,filemode.open)) {Binaryformat                ter formatter = new BinaryFormatter (); Return formatter.            Deserialize (stream) as TResult; }}//Deserialize XML file to type public static TResult deserializefromfilebyxml<tresult> (string path) where                Tresult:class {using (FileStream stream = new FileStream (path, FileMode.Open)) {                XmlSerializer formatter = new XmlSerializer (typeof (TResult)); Return formatter.            Deserialize (stream) as TResult; }        }    }

The method in the above case is implemented as a generic method with the addition of generic constraints to ensure generic security.

Serialization feature class with the following we built a book object, which we used to test our function classes.

    [Serializable] public class Book {[NonSerialized] private string _bookpwd;        [field:nonserialized] public event EventHandler namechanged;        private string _bookname;        private string _bookid;        Public ArrayList Albookreader;        public string _bookprice;        Public book () {albookreader = new ArrayList ();            } public string BookName {get {return _bookname;}                set {if (namechanged! = null) {namechanged (this, null);            } _bookname = value;        }} public void Bookpwd (string pwd) {_bookpwd=pwd;            } public string BookID {get {return _bookid;}        set {_bookid = value;}        The public void Setbookprice (string price) {_bookprice = Price; } [OndeserializedattriBute] public void ChangeName (StreamingContext context) {this.        BookName = "C # in Layman's";            } public void Write () {Console.WriteLine ("Book ID:" + BookID);            Console.WriteLine ("Book Name:" + bookname);            Console.WriteLine ("Book Password:" + _bookpwd);            Console.WriteLine ("Book Price:" + _bookprice);            Console.WriteLine ("Book Reader:");            for (int i = 0; i < Albookreader.count; i++) {Console.WriteLine (albookreader[i]); }        }    }

Key Introduction:
1.[serializable] Attribute definition The type can be serialized;

2.[nonserialized] defines that an attribute is not serialized, that is, an internal member is nonserialized to prohibit serialization of attribute tokens;

3.[field:nonserialized] Define events not to be serialized;

4.[ondeserializedattribute] When it is applied to a method, it specifies that the object is executed immediately after it is deserialized.

5.[ondeserializingattribute] When it is applied to a method, it is specified to be executed immediately when the object is deserialized.

6.[onserializedattribute] If you apply an object graph to a method, you specify whether to call this method after serializing the object graph.

7.[onserializingattribute] When it is applied to a method, it is specified to call this method before the object is serialized. 、

We use a console program for serialization and deserialization:

static void Main (string[] args)        {            string path = "c:\\test\\";            Book book = new book ();            Book. Namechanged + = new EventHandler (make_namechanged);            Book. BookID = "2001";            BOOK.ALBOOKREADER.ADD ("Abel");            BOOK.ALBOOKREADER.ADD ("Tomson");            Book. BookName = "Agile invincible";            Book. BOOKPWD ("* * * *");            Book. Setbookprice ("102.00");            Object Serialization            serializer.serializetofilebyxml<book> (book, Path, "Book.txt");            Object deserialization of book            anothorbookserialize = new book ();            Anothorbookserialize = serializer.deserializefromfilebyxml<book> (path + "Book.txt");            Anothorbookserialize. Write ();            Console.readkey ();        }        static void Make_namechanged (object sender, EventArgs e)        {            Console.WriteLine ("Name Changed");        }

Our case is to invoke the XML serialization stream file form, after the serialized execution of the file as follows:

<?xml version= "1.0"?>
<book xmlns:xsi= "http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd= "Http://www.w3.org/2001/XMLSchema" >
<alBookReader>
<anytype xsi:type= "Xsd:string" >Abel</anyType>
<anytype xsi:type= "Xsd:string" >Tomson</anyType>
</alBookReader>
<_bookPrice>102.00</_bookPrice>
<BookName> Agility </BookName>
<BookID>2001</BookID>
</Book>

The deserialized output is as follows:

Name Changed
Book id:2001
Book Name: Agile Invincible
Book Password:
Book price:102.00
Book Reader:
Abel
Tomson

Results Analysis:

[NonSerialized] The book Password property does not appear in the serialized XML file for book Password.

[Field:nonserialized] The Namechanged event does not appear in the serialized XML file namechanged.

The [Ondeserializedattribute]changename () method, which does not immediately execute the ChangeName () method after deserialization, does not change the book name name and requires a binary stream form to execute the method successfully.

    Serialization of    serializer.serializetofile<book> (book, Path, "Book.txt");    Deserialization    anothorbookserialize = serializer.deserializefromfile<book> (path + "Book.txt");

We take the XML stream as an example to better understand the serialization and deserialization of the execution process, the actual application of the majority of binary streams in the form of serialization and deserialization more.

Third, inherit the ISerializable interface more flexible control serialization process:

The ISerializable interface needs to be implemented when the above serializable feature is unable to satisfy the complex serialization process.

Here is the workflow of the formatter: if the formatter is serializing an object and discovers that the object implements the ISerializable interface, then he ignores all the serialization attributes of the class, and instead calls a SerializationInfo object of the GetObjectData method. Method is responsible for the addition of the object's properties internally. When deserializing, the object is called by a SerializationInfo object in a protected band parameter construction method, and the method internal object property is assigned a value.

The sub-type of the ISerializable interface we implement below should be responsible for the serialization of the parent type as an example:

1. The parent class also implements the ISerializable interface

 [Serializable] public class Person:iserializable {public string name{get;set;}            Public person () {} protected person (SerializationInfo Info,streamingcontext context) { Name = info.        GetString ("Name"); } public virtual void GetObjectData (SerializationInfo info, StreamingContext context) {info.        AddValue ("name", name); }} [Serializable] public class Employee:person, ISerializable {public int salary{get;set;} 
Public employee () {} protected employee (SerializationInfo info, StreamingContext context ) {Salary = info. GetInt32 ("Salary"); Name = info. GetString ("Name"); } public override void GetObjectData (SerializationInfo info, StreamingContext context) {base. GetObjectData (Info,context); Info. AddValue ("Salary", Salary); } }

Note: The GetObjectData method in the employee overrides the virtual method GetObjectData in the base class person.

Employee Employee = new Employee () {Name = "Abel", salary=1220}; Binaryserializer.serializetofile<employee> (Employee, strfile, "Employee.txt"); employee = Binaryserializer.deserializefromfile<employee> ("C:\\test\\employee.txt"); Console.WriteLine (employee. Name); Console.WriteLine (employee. Salary);

2. If the parent class does not implement the ISerializable interface how to handle it?

We are implementing a parent class of the employee class that inherits the ISerializable interface Person,person does not implement the ISerializable interface, and the serializer does not handle the person object by default, only by ourselves.

Here we use specific examples to achieve:

   [Serializable]    public class person    {public        string Name{get;set;}}    [Serializable]    public class Employee:person, ISerializable    {public        int salary{get;set;}        Public Employee ()        {        }        protected employee (SerializationInfo info, StreamingContext context)        {            Salary = info. GetInt32 ("Salary");            Name = info. GetString ("Name");        }        public void GetObjectData (SerializationInfo info, StreamingContext context)        {            info. AddValue ("name", name);            Info. AddValue ("Salary", Salary);        }    }

In this serialization learning we use the processing knowledge of events, generics, and stream files, which we can implement locally to load and remotely restore objects.

A serializer tool class is obtained that encapsulates the process of serialization and deserialization.

C # Serialization Understanding 2 (RPM)

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.