系列化入门读物XML:namespace prefix = o ns = "urn:schemas-microsoft-com:Office:office" />
这个指南描述如何轻松地系列化一个简单的对象。
这篇文章包含三个部分。
PART1 介绍基本的系列化
PART2 解释如何有效地读取无效数据和支持版本。
PART3 描述如何对复杂的对象进行系列化。
系列化是从永久存储媒体(例如:磁盘文件)读取或者写入对象的处理过程。系列化一个对象需要3个因素:1、一个CFile表示数据文件;2、一个CArchive对象提供对系列化上下文件的支持;对象是可系列化的。
.NET/develop/article/images/16246_1.jpg" align=baseline border=0>
对文件“foo.dat”中的对象进行系列化,需要用适当的方式打开文件。在这个例子中,文件打开只用了:read/write方式。
// Open file "foo.dat"
CFile* pFile = new CFile();
ASSERT (pFile != NULL);
if (!pFile->Open ("foo.dat", CFile::modeReadWrite | CFile::shareExclusive)) {
// Handle error
return;
}
// Create archive ...
bool bReading = false; // ... for writing
CArchive* pArchive = NULL;
try
{
pFile->SeekToBegin();
UINT uMode = (bReading ? CArchive::load : CArchive::store);
pArchive = new CArchive (pFile, uMode);
ASSERT (pArchive != NULL);
}
catch (CException* pException)
{
// Handle error
return;
}
int CFoo::serialize
(CArchive* pArchive)
{
int nStatus = SUCCESS;
// Serialize the object ...
...
return (nStatus);
}
class CFoo
{
// Construction/destruction
public:
CFoo::CFoo();
virtual CFoo::~CFoo();
// Methods
public:
int serialize (CArchive* pArchive);
// Data members
public:
CString m_strName; // employee name
int m_nId; // employee id
};
int CFoo::serialize
(CArchive* pArchive)
{
int nStatus = SUCCESS;
// Serialize the object ...
ASSERT (pArchive != NULL);
try
{
if (pArchive->IsStoring()) {
// Write employee name and id
(*pArchive) << m_strName;
(*pArchive) << m_nId;
}
else {
// Read employee name and id
(*pArchive) >> m_strName;
(*pArchive) >> m_nId;
}
}
catch (CException* pException)
{
nStatus = ERROR;
}
return (nStatus);
}
pArchive->Close();
delete pArchive;
pFile->Close();
delete pFile();
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/10752043/viewspace-993101/ ,如需转载,请注明出处,否则将追究法律责任。