Serialization with .NET - Other Attributes
(Page 4 of 4 )
Besides the OnDeserializing attribute, .NET contains other similar attributes. When one of these attributes is applied to a method, then the method is called in the appropriate stage of serialization or deserialization. Here's a simple class that makes use of this family of attributes:
using System;
using System.Runtime.Serialization;
[Serializable]
public class AttributeTest
{
[OnSerializing]
internal void OnSerializing(StreamingContext context)
{
Console.WriteLine("Serializing.");
}
[OnSerialized]
internal void OnSerialized(StreamingContext context)
{
Console.WriteLine("Serialized.");
}
[OnDeserializing]
internal void OnDeserializing(StreamingContext context)
{
Console.WriteLine("Deserializing.");
}
[OnDeserialized]
internal void OnDeserialized(StreamingContext context)
{
Console.WriteLine("Deserialized.");
}
}
Notice how all the methods look like the OnDeserializing method in our previous example in their return type and parameter. The attribute names should make it pretty easy to tell when each method is called. Nonetheless, let's see the serialization and deserialization of an instance of our type. However, instead of using a FileStream and wasting a file, let's use a MemoryStream:
using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
class AttributeDemo
{
public static void Main(string[] args)
{
AttributeTest test = new AttributeTest();
// Serialize it
MemoryStream myStream = new MemoryStream();
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(myStream, test);
// Deserialize it
myStream.Position = 0;
test = (AttributeTest)formatter.Deserialize(myStream);
myStream.Close();
}
}
Serializing.
Serialized.
Deserializing.
Deserialized.
| DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware. |