Serialization

Section 18.5 demonstrated how to write the individual fields of a Record object to a text file, and Section 18.6 demonstrated how to read those fields from a file and place their values in a Record object in memory. In the examples, Record was used to aggregate the information for one record. When the instance variables for a Record were output to a disk file, certain information was lost, such as the type of each value. For instance, if the value "3" is read from a file, there is no way to tell if the value came from an int, a string or a decimal. We have only data, not type information, on disk. If the program that is going to read this data "knows" what object type the data corresponds to, then the data can be read directly into objects of that type. For example, in Fig. 18.9, we know that we are inputting an int (the account number), followed by two strings (the first and last name) and a decimal (the balance). We also know that these values are separated by commas, with only one record on each line. So, we are able to parse the strings and convert the account number to an int and the balance to a decimal. Sometimes it would be easier to read or write entire objects. C# provides such a mechanism, called object serialization. A serialized object is an object represented as a sequence of bytes that includes the object's data, as well as information about the object's type and the types of data stored in the object. After a serialized object has been written to a file, it can be read from the file and deserializedthat is, the type information and bytes that represent the object and its data can be used to recreate the object in memory.

Class BinaryFormatter (namespace System.Runtime.Serialization.Formatters.Binary) enables entire objects to be written to or read from a stream. BinaryFormatter method Serialize writes an object's representation to a file. BinaryFormatter method Deserialize reads this representation from a file and reconstructs the original object. Both methods throw a SerializationException if an error occurs during serialization or deserialization. Both methods require a Stream object (e.g., the FileStream) as a parameter so that the BinaryFormatter can access the correct stream. As you will see in Chapter 23, Networking: Streams-Based Sockets and Datagrams, serialization can be used to transmit objects between applications over a network.

In Sections 18.8 and 18.9, we create and manipulate sequential-access files using object serialization. Object serialization is performed with byte-based streams, so the sequential files created and manipulated will be binary files. Binary files are not human readable. For this reason, we write a separate application that reads and displays serialized objects.

Категории