C # Object serialization (2)

Source: Internet
Author: User
Tags object serialization
C # Object serialization (2) by: 23:42:29 Source: Tao Internet

Analysis

Object serialization can save object data permanently. The object state can be a derived type of ssytem. Io. stream. Not all types of objects can be serialized. This object can be serialized only when its type is defined as serializable. For example, to customize a class type, when the class type is marked with the [serializable] feature, its object can be serialized. The serialized code is simple and can be saved in multiple formats (or object graphs), such as binary, soap, and XML.

To serialize an object in binary format, you need to use the binaryformatter type, which is located in the mscorlib. dll assembly. You only need to import the object to its namespace when using it. The program code is shown in the following code:

// Import the namespace of the binaryformatter class
Using system. runtime. serialization. formatters. Binary;
// Create the binaryformatter Class Object mybf
Binaryformatter mybf = new binaryformatter ();
// Create the object reference OBJ of the custom class myclass, which has marked the [serializable] Feature
Myclass OBJ = new myclass ();
// Create a stream type reference FS
Stream FS = new filestream (path to be saved, filemode. Create,
Fileaccess. Write, fileshare. None );
// Call the serialize method of mybf and pass the FS and OBJ Parameters
Mybf. serialize (FS, PN );
// Close the FS object
FS. Close ();

You can call the serialize () method of the binaryformatter class object to complete the serialization operation. If the SOAP format is used for serialization, the operation is basically the same as the binary format, but the serialize () method is called by the soapformatter class object. Because the namespace of the soapformatter class is defined as system. runtime. serialization. formatters. soap, and this namespace is defined in system. runtime. serialization. formatters. soap. DLL assembly, so when using the soapformatter class, you need to manually reference the assembly, and then import the namespace. In fact, the binaryformatter class and soapformatter class both implement the iformatter interface. Therefore, you can compile the corresponding multi-State program in the program application.

To serialize objects in XML format, you must create a system. xml. serialization. xmlserializer Class Object and call the serialize () method. Although the namespace of this class is defined in system. XML. but Visual Studio 2005/Visual Studio 2008 will automatically reference this assembly, so you do not need to manually reference the system. XML. DLL assembly. The serialization method in XML format is shown in the following code:

// Import the namespace of the xmlserializer class
Using system. xml. serialization;
// Create the xmlserializer Class Object myxs
Xmlserializer myxs = new xmlserializer (typeof (myclass ),
Type array of other objects to be serialized );
// Create the object reference OBJ of the custom class myclass, which has marked the [serializable] Feature
Myclass OBJ = new myclass ();
// Create a stream type reference FS
Stream FS = new filestream (path to be saved, filemode. Create,
Fileaccess. Write, fileshare. None );
// Call the serialize method of myxs to pass the FS and OBJ Parameters
Myxs. serialize (FS, PN );
// Close the FS object
FS. Close ();

The xmlserializer class constructor needs to pass parameters. When you only need to implement an independent object, you can pass the type object type of the class to which the object belongs. When the object depends on other objects, you need to pass the type object type of the class to which other objects belong as an array.

Description: an object graph refers to a group of associated object relationships, which describes the dependencies between multiple objects.

Interview example 21: How to deserialize objects in XML format persistence?

Test site: basic method of deserialization to process object data after deserialization.

Frequency:★★

Answer

Create a C # Windows Forms Application project in Visual Studio 2005/Visual Studio 2008 and name the project listserialize. The objects serialized by the program are the objects of the List <t> class (this class is serializable). Add the subitem in the list <t> class object through the "add" button control, click "output XML. Click the "XML deserialization" button to restore the object information in the specified XML file, and output each sub-item data of the object in the ListBox control (named "xmllist. Create a basic form layout and control in the "form1.cs [design]" view of Visual Studio 2005/Visual Studio 2008. The control name is 7.50.

(Click to view the big chart) Figure 7.50 layout and name of the deserialization Form Control

Compile the form1.cs file of the listserialize project, as shown in code 7.26.

Code 7.26 deserialization object: form1.cs

Using system;
.............................................
// Import necessary namespaces
Using system. xml. serialization;
Using system. runtime. serialization;
Using system. IO;

 

Namespace listserialize
{
Public partial class form1: Form
{
// Create a list <t> type Object List. The subitem type is persondetail.
List <persondetail> List = new list <persondetail> ();
// Declare the list <t> type readlist variable. The subitem type is persondetail.
List <persondetail> readlist;
// Declare the FN variable for storing the file path
String FN;
Public form1 ()
{
Initializecomponent ();
}

 

Private void addbtn_click (Object sender, eventargs E)
{
// Create a persondetail object PD
Persondetail Pd = new persondetail ();
// Assign the two text box controls to the two objects of PD
PD. Name = nametxt. text;
PD. Password = passwordtxt. text;
// Add subitem PD to the list object
List. Add (PD );
MessageBox. Show ("added successfully ");
}

 

Private void outputbtn_click (Object sender, eventargs E)
{
// Obtain the file path entered by the user
Fn = filename. text;
// Create an object for xmlserializer to reference Xs and pass the list <persondetail> type
Xmlserializer xs = new xmlserializer (typeof (list <persondetail> ));
// Create a stream type reference FS and pass FN as the path Parameter
Stream FS = new filestream (FN, filemode. Create, fileaccess. Write, fileshare. None );
// Call the serialize method of Xs to pass the FS and LIST Parameters
Xs. serialize (FS, list );
// Close the FS object
FS. Close ();
MessageBox. Show ("XML serialization successful ");
// Clear the text box Control
Nametxt. Text = "";
Passwordtxt. Text = "";
Filename. Text = "";
}

 

Private void inputbtn_click (Object sender, eventargs E)
{
String STR;
// Obtain the file path entered by the user
Fn = readfilename. text;
Try
{
// Create a filestream type to reference FS and pass FN as the path parameter. The file mode is to open the file.
Filestream FS = new filestream (FN, filemode. Open );
// Create the xmlserializer type object Xs and pass the list <persondetail> type
Xmlserializer xs = new xmlserializer (typeof (list <persondetail> ));
// Call the deserialize method of Xs to pass the FS
// Convert the returned object to the list <persondetail> type and assign the reference value to readlist
Readlist = (list <persondetail>) XS. deserialize (FS );
// Traverse each subitem of readlist
Foreach (persondetail PD in readlist)
{
// Combine the attribute values of the subitem and assign them to the STR variable.
STR = string. Format ("Name: [{0}], password: [{1}]", PD. Name, PD. Password );
// Call the Add method of the xmllist control items to add STR as an item
Xmllist. Items. Add (STR );
}
}
// An error occurred while processing the file.
Catch (filenotfoundexception ex)
{
String MSG = string. Format ("exception message: {0}", Ex. Message );
MessageBox. Show (MSG );
}
// Clear the file path text box Control
Readfilename. Text = "";
}
}

 

Public class persondetail
{
// Define two private fields
String _ name;
String _ password;
// Define two public attributes to read and write the corresponding private fields
Public string name
{
Get
{
Return _ name;
}
Set
{
_ Name = value;
}
}
Public String Password
{
Get
{
Return _ password;
}
Set
{
_ Password = value;
}
}
Public persondetail (){}
}
}

After the program runs, enter a group of values in the first two textbox controls and click Add. Result 7.51 is displayed.

Each time you click the "add" button, a subitem is added to the List object, which is an object of the persondetail class initialized based on the user input value. After the subitem is added, the information dialog box shown in 7.51 is displayed. After multiple adding operations, enter the file name of any XML file in the text box control with the name attribute "readfilename" and click the "output XML" button to complete XML format serialization. You can input the XML file name created by the serialization operation to the text box control with the name attribute readfilename again, and then click the XML deserialization button to complete the data deserialization operation in the XML file, the running result is 7.52.

Figure 7.51 serialization in XML format
(Click to view the big image) Figure 7.52 deserializes the XML file and outputs it

Based on the input value, the data of the created list object has been deserialized and displayed in the list box control with the name attribute "xmllist.

Analysis

Deserialization is a serialized reverse operation. Since the serialization operation needs to be written to the stream, deserialization reads the stream and extracts the object data. For example, there is a "person. dat "file, which persists known types of objects (such as the personname class) in binary format. The deserialization method is shown in the following code:

// Import the namespace of the binaryformatter class
Using system. runtime. serialization. formatters. Binary;
// Create the binaryformatter Class Object mybf
Binaryformatter mybf = new binaryformatter ();
// Create a filestream reference FS to read the "person. dat" File
Filestream FS = new filestream ("person. dat", filemode. Open );
// Call the deserialize method of mybf and pass the FS Parameter
Personname Pn = (personname) mybf. deserialize (FS );
// Close the FS object
FS. Close ();

In the above Code, the program obtains the reference Pn of the personname class object, which is created based on the deserialization of the "person. dat" file to restore the data of the original object.

Interview example 22: How to customize serialization?

Test site: Understand custom serialization and learn custom serialization methods.

Frequency:★★★★

Answer

Create a C # windows form application project in Visual Studio 2005/Visual Studio 2008 and name the project customserialize. The program can create an object based on user input values, serialize the object in binary format, and persist the object to the specified path. In this process, the field value of the object is added to a string, and the key name corresponding to the field value is also changed to the specified value, rather than the field name. During the deserialization process, the field data value of the object is changed to the original value, so it seems that the object data has not been modified. Create a basic form layout and control in the "form1.cs [design]" view of Visual Studio 2005/Visual Studio 2008. The control name is 7.53.

(Click to view the big chart) Figure 7.53 customize the layout and name of the serialized Form Control

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.