對象序列化(四):多個物件序列化

來源:互聯網
上載者:User

前幾個日記都是介紹單個對象序列化的,其實,可以在序列化過程中向流連續寫入多個對象。

繼續前面的樣本,如果是多個學生對象

//學生對象
private List<CollegeStudent> stus = new List<CollegeStudent>();

需要儲存資料時,將集合中的對象序列化到檔案中:

//將學生清單序列化到檔案中
        private void SerializeStudentList(String FileName, List<CollegeStudent> stus)
        {
            using (FileStream writer = new FileStream(FileName, FileMode.Create))
            {
                IFormatter formatter = new BinaryFormatter();

                foreach (CollegeStudent stu in stus)
                    formatter.Serialize(writer, stu);

                MessageBox.Show("對象成功儲存到檔案:" + FileName);
            }
        }

 

相應地,需要讀取資料時,從檔案流中還原序列化出各個對象,然後將其加入到對象集合中:

//從檔案中還原序列化對象
        private void DeserializeStudentList(String FileName, List<CollegeStudent> stus)
        {
            using (FileStream reader = new FileStream(FileName, FileMode.Open))
            {
                IFormatter formatter = new BinaryFormatter();
                while (reader.Position < reader.Length)
                {
                    stus.Add(formatter.Deserialize(reader) as CollegeStudent);
                }
            }
        }

由於在還原序列化時無法預知檔案中到底有多少個對象,所以採用直接判斷流存取指標是否已到流末尾的方法,利用while迴圈還原序列化所有的對象並加入集合中。

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.