MFC 序列化機制 (CArchive + Serialize) 預設僅在 Doc/View 架構下自動觸發。對話框專案若想復用此機制,需自行管理檔案開啟/關閉並顯式呼叫 Serialize。
CMyDiaryApp 重寫 Serializevoid CMyDiaryApp::Serialize(CArchive& ar) {
WORD nCount;
if(ar.IsStoring()) {
nCount = (WORD)m_diaryList.GetCount();
ar << nCount;
POSITION pos = m_diaryList.GetHeadPosition();
while(pos) {
CDiary* p = m_diaryList.GetNext(pos);
ar << p->m_date; // 假設 CDiary 只序列化日期示範
}
ASSERT(nCount == 0);
} else {
ar >> nCount;
while(nCount--) {
CDiary* p = new CDiary;
ar >> p->m_date;
m_diaryList.AddTail(p);
}
}
}
void CMyDiaryApp::OnRead() {
CFile file;
if(file.Open(_T("diary.dat"), CFile::modeRead)) {
CArchive ar(&file, CArchive::load);
Serialize(ar); // 關鍵:手動調用
ar.Close(); file.Close();
}
}
void CMyDiaryApp::OnSave() {
CFile file;
if(file.Open(_T("diary.dat"), CFile::modeCreate|CFile::modeWrite)) {
CArchive ar(&file, CArchive::store);
Serialize(ar);
ar.Close(); file.Close();
}
}
void CMyDialog::OnBtnLoad() { ((CMyDiaryApp*)AfxGetApp())->OnRead(); RefreshList(); }
void CMyDialog::OnBtnSave() { ((CMyDiaryApp*)AfxGetApp())->OnSave(); }
Serialize,避免讀/寫代碼重複ar.GetObjectSchema()) 與多態序列化 (RUNTIME_CLASS)CFile::modeCreate|modeWrite 會截斷既有檔案,確認無誤再存CFileException、CArchiveException 需捕獲