#using <mscorlib.dll>
using namespace System;
using namespace System::IO;
using namespace System::Collections;
using namespace System::Runtime::Serialization::Formatters::Binary;
using namespace System::Runtime::Serialization;
// This class is serializable and will have its OnDeserialization method
// called after each instance of this class is deserialized.
[Serializable]
__gc class Circle : public IDeserializationCallback
{
Double m_radius;
// To reduce the size of the serialization stream, the field below is
// not serialized. This field is calculated when an object is constructed
// or after an instance of this class is deserialized.
public:
[NonSerialized]
Double m_area;
public:
Circle(Double radius)
{
m_radius = radius;
m_area = Math::PI * radius * radius;
}
void OnDeserialization(Object* /*sender*/)
{
// After being deserialized, initialize the m_area field
// using the deserialized m_radius value.
m_area = Math::PI * m_radius * m_radius;
}
public:
String* ToString()
{
return String::Format(S"radius= {0}, area= {1}", __box(m_radius), __box(m_area));
}
};
void Serialize()
{
Circle* c = new Circle(10);
Console::WriteLine(S"Object being serialized: {0}", c);
// To serialize the Circle, you must first open a stream for
// writing. We will use a file stream here.
FileStream* fs = new FileStream(S"DataFile.dat", FileMode::Create);
// Construct a BinaryFormatter and use it to serialize the data to the stream.
BinaryFormatter* formatter = new BinaryFormatter();
try
{
formatter->Serialize(fs, c);
}
catch (SerializationException* e)
{
Console::WriteLine(S"Failed to serialize. Reason: {0}", e->Message);
throw;
}
__finally
{
fs->Close();
}
}
void Deserialize()
{
// Declare the Circle reference.
Circle* c = 0;
// Open the file containing the data that we want to deserialize.
FileStream* fs = new FileStream(S"DataFile.dat", FileMode::Open);
try
{
BinaryFormatter* formatter = new BinaryFormatter();
// Deserialize the Circle from the file and
// assign the reference to our local variable.
c = dynamic_cast<Circle*>(formatter->Deserialize(fs));
}
catch (SerializationException* e)
{
Console::WriteLine(S"Failed to deserialize. Reason: {0}", e->Message);
throw;
}
__finally
{
fs->Close();
}
// To prove that the Circle deserialized correctly, display its area.
Console::WriteLine(S"Object being deserialized: {0}", c);
}
[STAThread]
int main()
{
Serialize();
Deserialize();
}