Class serialization in C #

Source: Internet
Author: User
Tags object serialization

1. What is serialization?

Serialization is the process of converting the object state to a format that can be maintained or transmitted. During the serialization process, the public and private fields of the object and the name of the class (including the Assembly containing the class) are converted to byte streams and then written to the data stream. In contrast to serialization, deserialization converts a stream into an object. These two processes can be combined to easily store and transmit data.

2. Why serialization?

One reason is to keep the object state in the storage media so that you can recreate an exact copy later.

We often need to save the field value of the object to the disk and retrieve the data later. Although this can be done without serialization, this method is often cumbersome and error-prone, and will become more and more complex when you need to trace the object hierarchy. Imagine writing a large business application that contains a large number of objects. programmers have to write code for each object to save fields and attributes to the disk and restore these fields and attributes from the disk. Serialization provides a quick way to easily achieve this goal.

Another reason is that an object is sent from one application domain to another by value.

For example, serialization can be used to save the session state in ASP. NET and copy the object to the clipboard of Windows Forms. Remote processing can also use serialization to pass objects from one application domain to another through values.

The Common Language Runtime (CLR) manages the distribution of objects in the memory. the. NET Framework uses reflection to provide an automatic serialization mechanism. After the object is serialized, the class name, assembly, and all data members of the class instance are written to the storage media. Objects usually use member variables to store references to other instances. After the class is serialized, the serialization engine tracks all serialized reference objects to ensure that the same object is not serialized multiple times .. The serialization architecture provided by the. NET Framework can automatically and correctly process object charts and circular references. The only requirement for object charts is that all objects referenced by objects being serialized must be marked as serializable (see Basic serialization ). Otherwise, an exception occurs when the serialization program attempts to serialize unlabeled objects.
When deserializing A serialized class, the class is re-created and the values of all data members are automatically restored.

(Serialization technology has two main purposes: Persistent storage and value-based delivery .)

 

3. How to Implement Object serialization and deserialization

To serialize an object, ensure that the object can be serialized. In addition, serialization only saves the object attributes effectively, but some methods of the object cannot be serialized.
The easiest way to implement serializable class serialization is to add the serializable attribute tag class.
This class can be serialized. Note that the serialized class must be public, otherwise it cannot be serialized.


To serialize an instance of this class to a file,. NET Framework provides three methods:


XML serialization

Add the system. runtime. serialization. formatters. Binary namespace;

Binary serialization

Add the system. xml. serialization namespace;

The noserialized attribute is replaced by the xmllgnore attribute;

Soap serialization

Typical application: Web service.

 


4. Implement custom serialization

If you are not fully satisfied with the data stream organization method, you can implement the interface iserializable in the Custom class to customize serialization. This interface has only one method: getobjectdata, this method is used to fill in the data required for serialization of class objects into the serializationinfo object.
You also need to provide a formatting constructor. The parameter list of this constructor is the same as that of getobjectdata and must be declared as private. The purpose of this formatter is to construct the serializationinfo object and then call getobjectdata during serialization.


Example:

Using system; using system. data; using system. configuration; using system. web; using system. web. security; using system. web. ui; using system. web. UI. webcontrols; using system. web. UI. webcontrols. webparts; using system. web. UI. htmlcontrols; using system. runtime. serialization; using system. runtime. serialization. formatters. binary;/** // <summary> // description of the abstract of employee /// </Summary> [serializable] public class employee: iserializable {public int empid = 100; Public String empname = ""; [nonserialized] Public String noserialstring = "noserialstring-test"; public employee () {// todo: add the constructor logic //} private employee (serializationinfo info, streamingcontext ctxt) {empid = (INT) info. getvalue ("employeeid", typeof (INT); empname = (string) info. getvalue ("employeename", typeof (string); // noserialstring = (string) info. getvalue ("employeestring", typeof (string);} public void getobjectdata (serializationinfo, streamingcontext ctxt) {info. addvalue ("employeeid", empid); info. addvalue ("employeename", empname); // info. addvalue ("employeestring", noserialstring );}}

 

C # serialization and deserialization methods:

 

Public void otheremployeeclasstest () {employee MP = new employee (); MP. empid = 10; MP. empname = "Qiu Feng"; MP. noserialstring = "hello"; stream steam = file. open ("C: \ temp3.dat", filemode. create); binaryformatter BF = new binaryformatter (); response. write ("Writing employee info:"); BF. serialize (steam, MP); steam. close (); MP = NULL; // C # deserialization of serialization and deserialization stream steam2 = file. open ("C: \ temp3.dat", filemode. open); binaryformatter bf2 = new binaryformatter (); response. write ("reading employee info:"); employee MP2 = (employee) bf2.deserialize (steam2); steam2.close (); response. write (mp2.empid); response. write (mp2.empname); response. write (mp2.noserialstring );}

 

Address: http://skybirdzw.blog.163.com/blog/static/7257062620125371316992/

Class serialization in C #

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.