对话框中的序列化读写

  • 来源: 编程中国 作者: 若水   2008-05-14/21:59
  • 大家知道序列化读写函数Serialize在文档视图的打开和关闭的时候能自动调用,对于数据的读写非常方便
    那在对话抗中能否同样的利用这个Serialize函数呢?答案是肯定的。
    比如我们可以重载Serialize函数如下
    void CMyDiaryApp::Serialize(CArchive& ar)
    {
        POSITION pos;
        WORD nCount;

        if (ar.IsStoring())
        {    // storing code
            nCount = (WORD) m_DiaryList.GetCount();
            ar << nCount;
            pos = m_DiaryList.GetHeadPosition();
            while(pos!=NULL)
            {
                CDiary * pDiary = m_DiaryList.GetNext(pos);
                ar << pDiary->m_date;
                nCount--;
            }
            ASSERT(nCount == 0);
        }
        else
        {    // loading code
            ar >> nCount;
            while(nCount--)
            {
                CDiary * pDiary = new CDiary;
                ar >> pDiary->m_date;
                m_DiaryList.AddTail(pDiary);
            }
        }
    }
    由于在对话框编辑中不会自动调用Serialize函数,于是可以自己编写OnRead()和OnSave()函数来显示的调用Serialize函数,从而达到合理的使用Serialize函数,重获序列化读写模式给我们带来的便捷,具体如下:
    void CMyDiaryApp::OnRead()
    {
        CFile file;
        if(file.Open("diary.dat",CFile::modeRead))
        {
            CArchive ar(&file,CArchive::load);
            Serialize(ar); // 调用 Serialize
            ar.Close();
            file.Close();
        }
    }

    void CMyDiaryApp::OnSave()
    {
        CFile file;
        if(file.Open("diary.dat",CFile::modeCreate|CFile::modeWrite))
        {
            CArchive ar(&file,CArchive::store);
            Serialize(ar); // 调用 Serialize
            ar.Close();
            file.Close();
        }
    }
    然后对于 void CMyDiaryApp::OnSave()和 void CMyDiaryApp::OnRead()函数,我们在需要的时候可以随意的使用,通过上述方式,我们就达到了我们的目的

     


    评论 {{userinfo.comments}}

    {{money}}

    {{question.question}}

    A {{question.A}}
    B {{question.B}}
    C {{question.C}}
    D {{question.D}}
    提交

    驱动号 更多