程序構架搭建入門

數據的保存技術

使用文檔進行數據保存

問題

  1. 當對象屬性發生變化時,需要增加或減少信息的寫入和讀取次數

  2. 信息的安全性較差

序列化和反序列化

注意:

  1. 只要是對象皆可進行序列化和反序列化操作

  2. 如果某個數據對象要進行序列化和反序列化操作,首先要將這個對象進行添加特性-序列化標識

對象數據進行序列化保存

 private void btnSavesl_Click(object sender, EventArgs e)
        {
            //首先數據封裝
            objStudent student = new objStudent()
            {
                ID = int.Parse(txtID.Text.Trim()),
                Name = txtName.Text.Trim(),
                Age = int.Parse(txtAge.Text.Trim()),
                Birthday = txtBirthday.Text.Trim()
            };
            //【1】創建文件流
            FileStream fs = new FileStream("Student.stu",FileMode.Create);
            //【2】創建二進制格式化器
            BinaryFormatter formatter = new BinaryFormatter();
            //【3】調用這個格式化器的序列化方法
            formatter.Serialize(fs,student);
            fs.Close();
        }

對象數據反序列化讀取

 private void btnReadersl_Click(object sender, EventArgs e)
        {
            //【1】創建文件流
            FileStream fs = new FileStream("Student.stu", FileMode.Open);
            //【2】創建二進制格式化器
            BinaryFormatter formatter = new BinaryFormatter();
            //【3】調用反序列化方法
            objStudent student=(objStudent)formatter.Deserialize(fs);
            fs.Close();
            txtID.Text = student.ID.ToString();
            txtName.Text = student.Name;
            txtAge.Text = student.Age.ToString();
            txtBirthday.Text = student.Birthday;
        }

應用場合

  1. 應用程序配置信息(如果信息量較大,則使用該方法更方便讀取和寫入)

  2. 不需要數據庫的時候,可以作爲數據存取的載體

  3. WebServerice等服務中對象的傳遞

  4. 模塊之間的數據傳遞

    https://www.cnblogs.com/jpfss/p/8397596.html

好處

  1. 對象數據的存取更方便,擴展性強

  2. 數據安全性更強

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章