串行化可使对象被转换为某种外部的形式,比如以文件存储的形式供程序使用,或通过
程序间的通讯发送到另一个处理过程。转换为外部形式的过程称为"串行化",而逆过程称为"反串行化"。
简介
请看例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();
}
在标记1中,我们定义了一个BinaryFormatter类型的变量,此种类型的任意对象都可以二进制的形式进行串行与反串行化。
在标记2中,用指定的名称创建了一个新的文