In-depth C # Learning Series 1: serialize and deserialize)

Source: Internet
Author: User
Serialization, also known as serialization, is a mechanism used by the. NET runtime environment to support user-defined streaming. The objective is to make the custom object persistent by storage, or to transmit the object from one place to another.
The. NET Framework provides two serializing methods: 1. Using binaryformatter for serialization; 2. Using soapformatter for serialization; 3. Using xmlserializer for serialization. The first method provides a simple binary data stream and some additional types of information, while the second method formats the data stream for XML storage. The third method is similar to the second method in XML format storage, it is much simpler than the second XML format (removes the extra information unique to soap ).
You can use the [serializable] attribute to serialize a class. If the elements of a class do not want to be serialized, 1 and 2 can use the [nonserialized] attribute for flag. 2. You can use the [xmlignore] flag.
1. Use binaryformatter for serialization
The following is a serializable class:
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. IO;
Using
System. runtime. serialization. formatters. Binary;
/// <Summary>
/// Summary of classtoserialize
/// </Summary>
[Serializable]
Public class classtoserialize
{
Public int id = 100;
Public string name = "name ";
[Nonserialized]
Public String sex = "male ";
}


The following describes the serialization and deserialization methods:
Public void serializenow ()
{
Classtoserialize c = new classtoserialize ();
Filestream = new filestream ("C: \ Temp. dat", filemode. Create );
Binaryformatter B = new binaryformatter ();
B. serialize (filestream, C );
Filestream. Close ();
}
Public void deserializenow ()
{
Classtoserialize c = new classtoserialize ();
C. Sex = "KKKK ";
Filestream = new filestream ("C: \ Temp. dat", filemode. Open, fileaccess. Read, fileshare. Read );
Binaryformatter B = new binaryformatter ();
C = B. deserialize (filestream) as classtoserialize;
Response. Write (C. Name );
Response. Write (C. Sex );
Filestream. Close ();
}


Call the above two methods to see the serialized result: the sex attribute is always null because it is marked as [nonserialized.
2. Use soapformatter for serialization
Similar to binaryformatter, you only need to make a simple modification:
A. Change. formatter. Binary in the using statement to. formatter. Soap;
B. replace all binaryformatter with soapformatter.
C. Make sure that the file name is. xml.
After the above simple changes, soapformatter can be serialized. The generated file is an XML file.
3. Use xmlserializer for serialization
There is another question about the formatter. Suppose we need XML, but we do not want additional information unique to soap. What should we do? There are two solutions: either compile a class that implements the iformatter interface, using a method similar to the soapformatter class, but there is no information you don't need; or use the library class xmlserializer, this class does not use the serializable attribute, but it provides similar functions.
If we don't want to use the mainstream serialization mechanism, but want to use xmlseralizer for serialization, we need to modify it as follows:
A. Add the system. xml. serialization namespace.
B. the serializable and noserialized attributes are ignored, but the xmlignore attributes are used. Their behavior is similar to that of noserialized.
C. xmlseralizer requires the class to have a default constructor. This condition may already be met.
The following is an example:
Class to be serialized:
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;
UsingSystem. xml. serialization;
[Serializable]
Public class person
{
Private string name;
Public string name
{
Get
{
Return name;
}
Set
{
Name = value;
}
}


Public String sex;
Public int age = 31;
Public Course [] courses;

Public Person ()
{
}
Public Person (string name)
{
Name = Name;
Sex = "male ";
}
}
[Serializable]
Public class course
{
Public string name;
[Xmlignore]
Public String description;
Public Course ()
{
}
Public Course (string name, string description)
{
Name = Name;
Description = description;
}
}


Serialization and deserialization methods:
Public void xmlserialize ()
{
Person c = new person ("CYJ ");
C. Courses = new course [2];
C. Courses [0] = New Course ("English", "communication tools ");
C. Courses [1] = New Course ("Mathematics", "Natural Science ");
Xmlserializer xs = new xmlserializer (typeof (person ));
Stream stream = new filestream ("C: \ CYJ. xml", filemode. Create, fileaccess. Write, fileshare. Read );
Xs. serialize (stream, C );
Stream. Close ();
}
Public void xmldeserialize ()
{
Xmlserializer xs = new xmlserializer (typeof (person ));
Stream stream = new filestream ("C: \ CYJ. xml", filemode. Open, fileaccess. Read, fileshare. Read );
Person P = Xs. deserialize (Stream) as person;
Response. Write (P. Name );
Response. Write (P. Age. tostring ());
Response. Write (P. Courses [0]. Name );
Response. Write (P. Courses [0]. Description );
Response. Write (P. Courses [1]. Name );
Response. Write (P. Courses [1]. Description );
Stream. Close ();
}


Here, the description attribute value of the course class is always null, and this node is not found in the generated XML document, for example:
<? XML version = "1.0"?>
<Person xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance" xmlns: XSD = "http://www.w3.org/2001/XMLSchema">
<Sex> male </sex>
<Age> 31 </age>
<Courses>
<Course>
<Name> English </Name>
<Description> communication tool </description>
</Course>
<Course>
<Name> mathematics </Name>
<Description> natural science </description>
</Course>
</Courses>
<Name> CYJ </Name>
</Person>


4. Custom serialization
If you want to serialize the class but are not satisfied with the data stream organization method, you can customize the serialization behavior by implementing interfaces in the Custom class. This interface has only one method, getobjectdata. This method is used to fill in the data required for serializing class objects into the serializationinfo object. The formatter you use will construct the serializationinfo object, and then call getobjectdata during serialization. If the parent class of the class also implements iserializable, you should call the parent class implementation of getobjectdata.
If you implement iserializable, you must also provide a constructor with a specific prototype. The parameter list of this constructor must be the same as that of getobjectdata. This constructor should be declared private or protected to prevent careless developers from using it directly.
Example:
Classes that implement iserializable:
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>
/// Abstract description of employee
/// </Summary>
[Serializable]
Public class employee: iserializable
{
Public int empid = 100;
Public String empname = "Andy Lau ";
[Nonserialized]
Public String noserialstring = "noserialstring-test ";
Public Employee ()
{
//

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.