Analysis of serialization in. net

Source: Internet
Author: User

Abstract: This article briefly introduces the serialization concept in. Net and the method for implementing serialization in code. At the end of this article, we will introduce the use of serialization in the clone method.

Serialization Concept

Serialization is a mechanism in. Net to implement Object persistence (persistent. It is a process of converting the data in an object into a single element (usually stream. Its Inverse Process is deserialization. The core concept of serialization is to regard all the data of an object as an independent unit.

In general, serialization is required in two cases: 1) when we want to completely Save the current state of the object to the storage medium, so that we can accurately restore the object in the future; 2) When we want to pass an object from an application domain to another application space. For example, the Windows form program uses the serialization mechanism to copy and paste the clipboard.

. NET Framework supports two types of serialization: shallow serialization and deep serialization.

The so-called shallow serialization is to convert the value of the read-write attribute of the object into word throttling, while the data inside the object (data not exposed through the read-write attribute) is not converted. Xmlserializer and web services use this technology.

Deep serialization is more thorough than shallow serialization because it copies the actual values stored in the object's private variables to the byte stream. In addition, deep serialization also serialize the entire object graph. That is to say, if your object holds a reference to another object or a set referenced by another object, all these objects will be serialize. Binaryformatter, soapformatter, And. Net remoting both use the deep serialization technology. It is even used for losformatter to generate State data stored on the web form page.

This article focuses on Deep serialization.

Serialization Process

. NET Framework provides automatic serialization through reflection. When an object is serialized, its class name, assembly, and all data members of the class instance are written to the storage media. The serialization engine keeps track of all serialized object references to ensure that the same object references are serialized at most once.

Generally, a serialization process is triggered by the serialize method of formatter (such as binaryformatter. The object serialization process follows the following rules:

1. Check whether the formatter has a proxy selector ). If yes, check whether the proxy selector holds the given object type. If yes, iserializable. getobjectdata is called.

2. If formatter does not have a proxy selector or the proxy selector does not have an object type, check whether the object is marked with the serializable attribute. If no, a serializationexception is thrown.

3. If the object is marked as serializable, check whether the object has implemented the iserializable interface. If this interface is implemented, getobjectdata is called.

4. If the object does not implement the iserializable interface, use the default serialization policy to serialize the domain not marked by the nonserialized attribute.

 

Enable your class to be serialized

Through the analysis of the serialization process, we can see that there are two ways to enable a class to be serialized: 1) mark this class as serializable; 2) this class implements the iserializable interface and marks this class as serializable.

1. Mark the serializable attribute

Marking the serializable attribute is the basic method for serialization. A simple example:

[Serializable]

Public class person

{

Public string name = NULL;

Public int age = 0;

}

You can use binaryformatter to serialize the above class:

Person Sam = new person ();

Sam. Name = "Sam ";

Sam. Age = 24;

Iformatter formatter = new binaryformatter ();

Stream stream = new filestream ("Sam. dat ",

Filemode. Create, fileaccess. Write, fileshare. None );

Formatter. serialize (stream, Sam );

Stream. Close ();

This is simple. All you need to do is create a stream and a formatter instance, and then call the serialize method of formatter. The data passed through binaryformatter serialize can still be returned through binaryformatter deserialize. The method is as simple as serialize, so we will not go into details here.

If you do not want to serialize all the fields in the class, you can use the nonserialized attribute for selection. For example:

[Serializable]

Public class person

{

Public string name = NULL;

[Nonserialized]

Public int age = 0;

}

In this way, the age domain will not be serialized.

Note that the serializable attribute cannot be inherited. That is to say, if you want the derived class of person to be serialize, the derived class must also be marked by serializable. Otherwise, the serializationexception is returned.

Similarly, all references to other classes in the person class should be serialize .. Most classes in the. NET Framework implement the iserializable interface, but some classes are not implemented, such as imagelist. You can use the msdn library to go to a list of classes that implement the iserializable interface. Be careful when using classes that do not implement this interface.

 

2. Implement the iserializable Interface

The serializable attribute is very powerful, which makes serialize and deserialize very simple. But there are some advantages and disadvantages in everything. The automatic serialization method implemented by serializable is sometimes not flexible enough. We cannot fully control the behavior of serialize and deserialize, and sometimes their behavior is very important to us. So how can we control the behavior of serialize and deserialize? The answer is to implement the iserializable interface by yourself. The iserializable interface gives us greater freedom to control serialize and deserialize, but we will undoubtedly have to write more code L.

The following describes how to implement the iserializabe interface. The iserializable interface is located in the system. runtime. serialization namespace. The declaration is as follows:

Public inferface iserializable

{

Void getobjectdata (serializationinfo info,

Streamingcontext context );

}

It only has one getobjectdata method. Therefore, we must implement this method just like other interfaces. However, unlike other interfaces, for deserialization, we must also implement a special Constructor (I call this constructor "serialization constructor "), this constructor has the same parameter list as getobjectdata. Since this constructor is used exclusively for the reflection mechanism of. NET Framework in deserialize, we usually declare it as a protected or private mode. (Of course, if your class only needs serialize and does not need deserialize, you can also not implement this special constructor)

[Serializable]

Public class person: iserializable

{

Public string name = NULL;

Public int age = 0;

Public Person ()

{

}

Protected Person (serializationinfo, streamingcontext context)

{

Name = info. getstring ("name ");

Age = info. getint32 ("Age ");

}

Void iserializable. getobjectdata (serializationinfo info,

Streamingcontext context)

{

Info. addvalue ("name", name );

Info. addvalue ("Age", age );

}

}

By implementing the iserializable interface, we have the opportunity to control the serialize behavior in iserializable. getobjectdata and control the deserialize behavior in the "serialization constructor. This interface provides us with comprehensive and flexible information, so that we can even play tricks in these two methods. For example, we can change info. fulltypename in deserialize to get another object of different types than the object to be serialize.

 

Innovation

We have talked about the typical environment used by serialization. It is an area involving Object persistence, such as Object Storage and inter-process data transmission. But in fact, it can also be applied to many other places. The key is whether we can think of using serialization. Sometimes the mindset is terrible. For example, we can see how to use serialization [1] In the clone method.

If we want to implement the clone method for the person class, we usually write as follows:

[Serializable]

Public class person: icloneable

{

Public string name = NULL;

Public int age = 0;

Public object clone ()

{

Person = new person ();

Person. Name = Name;

Person. Age = age;

Return person;

}

}

If we use the serialization method, the clone function can be written as follows:

Public object clone ()

{

Memorystream stream = new memorystream ();

Binaryformatter formatter = new binaryformatter ();

Formatter. serialize (stream, this );

Stream. Position = 0;

Return formatter. deserialize (Stream );

}

From the two implementations, the use of serialization to implement the clone method does not seem to be of any benefit. However, if you are facing a complex class inheritance system, you must implement the clone method from the base class to the derived class. With the first implementation method, you will have to write a clone method for each class, and as the number of data members increases, this method will become longer and longer, in addition, errors may occur due to changes in data members (I have encountered several times that the member variables are added to the class, but the clone method is not updated in time, resulting in running errors. It is difficult to debug such errors ). Now you can see the advantages of serialization implementation? Yes, we only need to declare the clone method as virtual in the base class and implement it using the serialization method, and then ensure that the base class and derived class can be serialize, isn't all the above troubles solved?

Summary

In modern software projects, no matter what kind of project will involve the problem of Object Persistence more or less ,. net is no exception, whether it is Windows form, Asp. both net and web services need to process Object persistence. Serialization is the solution provided by. Net to solve this problem.

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.