串行化可使對象被轉換為某種外部的形式,比如以文件存儲的形式供程序使用,或通過程序間的通訊發送到另一個處理過程。轉換為外部形式的過程稱為"串行化",而逆過程稱為"反串行化"。
簡介
請看例1中的示例,其將多個對象類型的值寫入到一個新的磁盤文件中,關閉文件,接著再把這些值重新讀取到內存中。
例1:
using namespace System;
using namespace System::IO;
using namespace System::Runtime::Serialization::Formatters::Binary;
int main()
{
array<int>^ intArray = {10, 20, 30};
array<float,2>^ floatArray = {
{1.2F, 2.4F},
{3.5F, 6.8F},
{8.4F, 9.7F}
};
DateTime dt = DateTime::Now;
Console::WriteLine("dt >{0}<", dt);
/*1*/ BinaryFormatter^ formatter = gcnew BinaryFormatter;
//將數據串行化到一個文件
/*2*/ Stream^ file = File::Open("Sr01.ser", FileMode::Create);
/*3a*/ formatter->Serialize(file, "Hello");
/*3b*/ formatter->Serialize(file, intArray);
/*3c*/ formatter->Serialize(file, floatArray);
/*3d*/ formatter->Serialize(file, true);
/*3e*/ formatter->Serialize(file, dt);
/*3f*/ formatter->Serialize(file, 1000);
/*3g*/ formatter->Serialize(file, L'X');
/*3h*/ formatter->Serialize(file, 1.23456F);
/*4*/ file->Close();
//從文件中反串行化數據--即讀取數據
/*5*/ file = File::Open("Sr01.ser", FileMode::Open);
/*6a*/ String^ s = static_cast<String^>(formatter->Deserialize(file));
Console::WriteLine("String >{0}<", s);
/*6b*/ array<int>^ newIntArray =
static_cast<array<int>^>(formatter->Deserialize(file));
Console::WriteLine("newIntArray:");
for (int i = 0; i < newIntArray->Length; ++i)
{
Console::Write(" {0}", newIntArray[i]);
}
Console::WriteLine();
/*6c*/ array<float,2>^ newFloatArray =
static_cast<array<float,2>^>(formatter->Deserialize(file));
Console::WriteLine("newFloatArray:");
for (int i = 0; i < 3; ++i)
{
for (int j = 0; j < 2; ++j)
{
Console::Write(" {0}", newFloatArray[i,j]);
}
Console::WriteLine();
}
/*6d*/ bool b = static_cast<bool>(formatter->Deserialize(file));
Console::WriteLine("bool >{0}<", b);
/*6e*/ DateTime newDT = static_cast<DateTime>(formatter->Deserialize(file));
Console::WriteLine("newDT >{0}<", newDT);
/*6f*/ int v = static_cast<int>(formatter->Deserialize(file));
Console::WriteLine("int >{0}<", v);
/*6g*/ wchar_t c = static_cast<wchar_t>(formatter->Deserialize(file));
Console::WriteLine("wchar_t >{0}<", c);
/*6h*/ float f = static_cast<float>(formatter->Deserialize(file));
Console::WriteLine("float >{0}<", f);
/*7*/ file->Close();
}