C#.net entity class Serialization method Why do you want to serialize

Source: Internet
Author: User
Tags serialization
In order to transfer data, it is necessary to serialize the entity class as a carrier, and find some examples of serialization. I feel this introduction is easier to introduce below!
1. What is serialization
Serialization is the process of converting an object's state into a format that can be persisted or transmitted, and during serialization, the public and private fields of the object and the name of the class, including the assembly containing the class, are converted to a byte stream and then written to the data flow. The opposite of serialization is deserialization, which converts a stream to an object. These two processes combine to make it easy to store and transfer data.
2. Why the use of serialization
A. One reason is to keep the state of the object in storage media so that you can re-create the exact copy later.
We often need to save the field value of an object to disk and retrieve this data at a later time. Although this can be done without serialization, this approach is often cumbersome and error prone, and becomes more complex when you need to track the hierarchy of objects. Imagine writing a large business application that contains a large number of objects, and programmers have to write code for each object to save fields and properties to disk and restore those fields and properties from disk. Serialization provides a quick and easy way to achieve this goal.
B. Another reason is to send an object from one application domain to another by value.
For example, serialization can be used to save session state in ASP.net and copy objects to a Windows forms Clipboard. Remoting can also use serialization to pass an object from one application domain to another by using a value.
The common language Runtime (CLR) manages the distribution of objects in memory, and the. NET Framework provides an automatic serialization mechanism by using reflection. After the object is serialized, the name of the class, the Assembly, and all the data members of the class instance are written to the storage media. Objects typically use member variables to store references to other instances. Class is serialized, the serialization engine tracks all the serialized reference objects to ensure that the same object is not serialized multiple times. The serialization architecture provided by the. NET framework can automatically handle object charts and circular references correctly. The only requirement for an object graph is that all objects referenced by the object being serialized must be marked as Serializable (see Basic serialization). Otherwise, an exception occurs when the serializer attempts to serialize an Unlabeled object.
When a serialized class is deserialized, the class is re-created and the values of all data members are automatically restored.
3. How to achieve the serialization and deserialization of objects
To implement serialization of an object, first make sure that the object can be serialized. Furthermore, serialization simply saves the properties of an object effectively, and it cannot be serialized for some methods of the object.
The easiest way to implement a class serializable is to add the serializable attribute tag class. Such as:
[Serializable ()]
public class Meablock
{
private int m_id;
public string Caption;
Public Meablock ()
{
Constructors
}
}
The serialization of the class can be implemented. Note that the serialized class must be public, otherwise it cannot be serialized.
To serialize an instance of the class to a file. The. NET Framework provides two methods:
A. XML serialization
Using the XmLSerializer class, you can serialize the following items.
Public read/write properties and fields for public classes
A class that implements ICollection or IEnumerable. (Note that only collections are serialized and public properties are not.) )
XmlElement object.
XmlNode object.
The DataSet object.
To implement serialization of instances of the above class, refer to the following example:
Meablock Myblock = new Meablock ();
Insert code to set properties and fields of the object.
XmlSerializer myserializer = new XmlSerializer (typeof (Meablock));
To write to a file, create a StreamWriter object.
StreamWriter mywriter = new StreamWriter ("Myfilename.xml");
Myserializer.serialize (Mywriter, Meablock);
It is to be noted that XML serialization saves only the fields that are public, not the private fields.
The resulting XML file format is as follows:
<MEABlock>
<Caption>Test</Caption>
</MEABlock>
For deserialization of an object, the following are:
Meablock Myblock;
Constructs an instance of the XmlSerializer with the type
The object is being deserialized.
XmlSerializer myserializer = new XmlSerializer (typeof (Meablock));
To read the file, creates a FileStream.
FileStream myFileStream = new FileStream ("Myfilename.xml", FileMode.Open);
Calls the deserialize method and casts to the object type.
Myblock = (meablock) myserializer.deserialize (myFileStream)
B. Binary serialization
Unlike XML serialization, binary serialization can serialize all fields (both private and public) in an instance of a class. This makes it easier and more accurate to restore the copy of the object.
To implement serialization of instances of the above class, refer to the following example:
Meablock Myblock = new Meablock ();
Insert code to set properties and fields of the object.
IFormatter formatter = new BinaryFormatter ();
Stream stream = new FileStream ("Myfile.bin", Filemode.create,fileaccess.write, Fileshare.none);
Formatter. Serialize (stream, Myblock);
Stream. Close ();
For deserialization of an object, the following are:
IFormatter formatter = new BinaryFormatter ();
Stream stream = new FileStream ("Myfile.bin", FileMode.Open,FileAccess.Read, FileShare.Read);
Meablock Myblock = (meablock) formatter. Deserialize (stream);
Stream. Close ();
4. How to implement the serialization and deserialization of a custom visual control in disguise
For custom controls in WinForm, Because it inherits from the System.Windows.Form class and the form class inherits from MarshalByRefObject, the forms themselves cannot be serialized, and the form's implementation is based on Win32 GUI resources and cannot be detached from the current context.
Of course, you can implement serialization of controls in a flexible way. The memory class model is used here.
Defining a Memory class (which is actually a serializable entity class) is used to record a valid property of a control, and you need to serialize the control by simply copy the instance of the control to the memory class and turn it into a serialized operation that holds the memory class.
Deserialization is an inverse process. Deserializes the data stream into the memory class, and then generates the control instance based on the memory class's properties. Some events and methods for the control can continue to be used.
The WWF emphasizes the instantiation of the class because the workflow and the application are in different threads. The need to use classes as the carrier of data transfer, you need to define the class as public serialization into binary transmission

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.