C # Serialization Understanding 1 (RPM)

Source: Internet
Author: User
Tags soap

serialization, which is also serialized, is a mechanism used by the. NET runtime environment to support the flow of user-defined types. The purpose is to persist the custom object in some form of storage, or to transfer the object from one place to another.
. NET Framework provides two ways of serialization: 1, using BinaryFormatter for serialization, 2, serialization with SoapFormatter, 3, serialization with XmlSerializer. The first provides a simple binary data stream along with some additional type information, while the second formats the data stream as XML storage, and the third, in fact, is stored in the form of a second, almost XML format, except that it is much simpler than the second XML format (which removes SOAP-specific extra information).
You can use the [Serializable] property to mark a class as serializable. If the elements of a class do not want to be serialized, 1, 2 can use the [NonSerialized] property to flag, 2, you can use [XmlIgnore] to flag.
1. Using 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 description of Classtoserialize
</summary>
[Serializable]
public class Classtoserialize
{
public int id = 100;
public string name = "Name";
[NonSerialized]
public string Sex = "male";
}


Here's how serialization and crossdress are done:

public void Serializenow ()
{
Classtoserialize C = new Classtoserialize ();
FileStream 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 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 ();
}


You can see the serialized result by invoking both of these methods: The sex attribute is always null because it is marked as [NonSerialized].
2. Using SoapFormatter for serialization
Like BinaryFormatter, we just need to make simple changes:
A. Change the. Formatter.binary in the using statement to. Formatter.soap;
B. Replace all BinaryFormatter with SoapFormatter.
C. Ensure that the file name extension is. xml
Through the above simple changes, you can achieve SoapFormatter serialization, the resulting file is an XML format file.
3. Using XmlSerializer for serialization
There's one more question about formatters, assuming we need XML, but we don't want soap-specific extra information, so what should we do? There are two scenarios: either write a class that implements the IFormatter interface in a way similar to the SoapFormatter class, but no information you don't need, or use the Library class XmlSerializer, which does not use the serializable attribute. However, it provides similar functionality.
If we do not want to use the mainstream serialization mechanism and want to use Xmlseralizer for serialization we need to make a change:
A. Add the System.Xml.Serialization namespace.
The B.serializable and Noserialized properties are ignored, but use the XmlIgnore property, which behaves like noserialized.
The C.xmlseralizer requires the class to have a default constructor, which may already be satisfied.
Here's a look at the example:
The class to serialize:

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.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;
}
}


Methods of serialization and deserialization:

public void Xmlserialize ()
{
Person C = new person ("Cyj");
c.courses = new Course[2];
C.courses[0] = new Course ("English", "communication Tool");
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 ();
}


The Description property value for the course class here will always be null, and there is no such node in the generated XML document, such as:

<?xml version= "1.0"?>
<person xmlns:xsi= "http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd= "Http://www.w3.org/2001/XMLSchema" >
<Sex> Men </Sex>
<Age>31</Age>
<Courses>
<Course>
<Name> English </Name>
<Description> Communication Tools </Description>
</Course>
<Course>
<Name> Math </Name>
<Description> Natural Sciences </Description>
</Course>
</Courses>
<Name>cyj</Name>
</Person>


4. Custom serialization
If you want to allow users to serialize a class, but are not entirely satisfied with how the data flow is organized, you can customize the serialization behavior by implementing the interface in the custom class. This interface has only one method, GetObjectData. This method is used to populate the SerializationInfo object with the data required to serialize the class object. The formatter you use will construct the SerializationInfo object and then call GetObjectData when serialized. If the parent class of the class also implements ISerializable, then the parent class of the GetObjectData should be called to implement.
If you implement ISerializable, you must also provide a constructor with a specific prototype, which must have the same argument list as GetObjectData. This constructor should be declared private or protected to prevent careless developers from using it directly.
Examples are as follows:
class to 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>
Summary 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 ()
{
//
TODO: Add constructor logic here
//
}
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 info, StreamingContext ctxt)
{
Info. AddValue ("EmployeeId", EmpId);
Info. AddValue ("EmployeeName", EmpName);
Info. AddValue ("employeestring", noserialstring);
}
}


Methods of serialization and deserialization:

public void Otheremployeeclasstest ()
{
Employee MP = new Employee ();
Mp. EmpId = 10;
Mp. EmpName = "Chu 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;
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);
}

C # Serialization Understanding 1 (RPM)

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.