This article tries to use the simplest example to introduce how to do serialization.
The basic way of serialization is as follows: The object is sent to Formatter,formatter to serialize it to form a stream. This stream can be a file stream, or something else.
Here, we serialize a randomly generated array and save it to a file, then take it out of the file and deserialize it to retrieve the array.
The first is to define an array:
Dim Nums (Ten) as Integer
Then you generate the contents of the array:
Dim I as Integer
For i = 0 to 10
Nums (i) = Int (Rnd () * 500) + 100
Next
Serialization is accomplished by formatter objects. We want to create a new formatter object:
Dim Sfformatter as New System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
The BinaryFormatter is binary serialized. Other serialization methods you can find in the Runtime.Serialization.Formatters.
We also need a stream to be serialized as output:
Dim FStream as New FileStream ("1.dat", FileMode.Create)
Ready to work, you can now call the formatter Serialize method for serialization:
Sfformatter.serialize (FStream, Nums)
Finally, don't forget to close the stream:
Fstream.close ()
Deserialization is a very similar way, except that the formatter deserialize method is invoked. The code is like this:
Private Sub Deserialize ()
Dim FStream as New FileStream ("1.dat", FileMode.Open)
Dim Sfformatter as New System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
Nums = Sfformatter.deserialize (fstream)
Fstream.close ()
End Sub
Serialization is as simple as that. This is just a serialized array of integers. If you want to serialize the object of a custom class, you need to precede the definition of the class with the following:
<serializable () >
There are more advanced applications for serialization, for example, you can specify which members of a class cannot be serialized, and define their own serialization interfaces. This article ends here. If you want to learn more, go and find MSDN!
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