April 2014
Intermediate to advanced
960 pages
22h 9m
English
This appendix summarizes useful serialization topics and techniques.
To serialize and deserialize objects in XML format, you use the XmlSerializer class’s Serialize and Deserialize methods. The methods work only for classes that have a parameterless constructor, either the default constructor or one that you created. They also work only for public properties and fields. All other properties and fields are ignored.
To serialize an object, follow these steps.
XmlSerializer, passing its constructor the object’s type.TextWriter to hold the serialization.Serialize method, passing it the TextWriter and the object to serialize.The following code shows how a program might serialize a Customer object.
// Create a serializer that works with the Customer class.
XmlSerializer serializer = new XmlSerializer(typeof(Customer));
// Create a TextWriter to hold the serialization.
string serialization;
using (TextWriter writer = new StringWriter())
{
// Serialize the Customer.
serializer.Serialize(writer, customer);
serialization = writer.ToString();
}
// Display the serialization.
serializationTextBox.Text = serialization;
To deserialize a serialization, follow these steps.
XmlSerializer, passing its constructor the object’s type.TextReader from which to read the serialization.Deserialize method, passing it the TextReader. Cast the result into the object’s type.Read now
Unlock full access