实例解析C++/CLI的串行化[VC/C++编程]
本文“实例解析C++/CLI的串行化[VC/C++编程]”是由七道奇为您精心收集,来源于网络转载,文章版权归文章作者所有,本站不对其观点以及内容做任何评价,请读者自行判断,以下是其具体内容:
串行化可以使对象被转换为某种外部的情势,比方以文件存储的情势供程序利用,或通历程序间的通讯发送到另一个处理历程.转换为外部情势的历程称为"串行化",而逆历程称为"反串行化".
简介
请看例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();
}
以上是“实例解析C++/CLI的串行化[VC/C++编程]”的内容,如果你对以上该文章内容感兴趣,你可以看看七道奇为您推荐以下文章:
本文地址: | 与您的QQ/BBS好友分享! |