C# 序列化和反序列化

       序列化和反序列化C#    [Serializable]      

       什麼叫序列化?

       我們都知道對象是暫時保存在內存中的,不能用U盤考走了,有時爲了使用介質轉移對象,並且把對象的狀態保持下來,就需要把對象保存下來,這個過程就叫做序列化,通俗點,就是比如,一首歌《童年》,你不能直接將聲音拿走,而是要保存在 “ 童年.mp3 ” 這樣的文件中,纔可以拿走。

       什麼叫反序列化?

       就是再把介質中的東西還原成對象,用播放器播放 “ 童年.mp3 ”  的過程。就是再把介質中的東西還原成對象,把石子還原成人的過程。通常網絡程序爲了傳輸安全才這麼做。

       首先需要注意的是:

       可序列化的只有公共類、公共屬性、公共方法。

       C#  序列化和反序列化有3種方法:

        一、BinaryFormatter序列化方式。

        二、SoapFormatter序列化方式。

        三、XML序列化方式。


       第一步,我們縣創建一個實體類:

 

using System;

namespace WinFormTest
{
    /// <summary>
    /// 學生信息
    /// </summary>
    [Serializable]
   public class Student
    {
        public Student()
        {
            
        }

        public Student(string name,string no,int age,string sex)
        {
            this.Name = name;
            this.No = no;
            this.Age = age;
            this.Sex = sex;
        }

        public string Name { get; set; }
        public string No { get; set; }
        public int Age { get; set; }
        public string Sex { get; set; }
    }
}

        第二步:

         BinaryFormatter第一種序列化和反序列化的方法:


using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Windows.Forms;

namespace WinFormTest
{
    public partial class Form1 :Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Student student=new Student("李敏贊","1",24,"man");

            //創建一個格式化程序實例
            IFormatter formatter=new BinaryFormatter();

            string path = AppDomain.CurrentDomain.BaseDirectory + "/timestamps.txt";
            //創建一個文件流
            Stream stream=new FileStream(path,FileMode.OpenOrCreate,FileAccess.Write,FileShare.None);

            formatter.Serialize(stream,student);
            stream.Close();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            string path = AppDomain.CurrentDomain.BaseDirectory + "/timestamps.txt";
            Stream stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read);
            IFormatter formatter = new BinaryFormatter();
            Student student = (Student)formatter.Deserialize(stream);
            stream.Close();
            this.txtResult.Text = "姓名:" + student.Name+"\r\n"
                                  + "學號:" + student.No + "\r\n"
                                  + "年齡:" + student.Age + "\r\n"
                                  + "性別:" + student.Sex;
        }
    }
}

          第二種方法和第一種方法類同,只是使用的名稱控件有所不同:

          SoapFormatter序列化方式與BinaryFormatter序列化方式類似,只需要把
          IFormatter formatter = new BinaryFormatter()
          改成
          IFormatter formatter = new SoapFormatter(),
          並且引用程序集System.Runtime.Serialization.Formatters.Soap.dll(.net自帶的)
          using System;
          using System.IO;
          using System.Runtime.Serialization;
          using System.Runtime.Serialization.Formatters.Soap;

       

          第三種方法:

          使用的名稱空間有所改變:

          using System.Runtime.Serialization;
          using System.Xml.Serialization;

using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Windows.Forms;
using System.Xml.Serialization;

namespace WinFormTest
{
    public partial class Form1 :Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //Student student=new Student("李敏贊","1",24,"man");

            ////創建一個格式化程序實例
            //IFormatter formatter=new BinaryFormatter();

            //string path = AppDomain.CurrentDomain.BaseDirectory + "/timestamps.txt";
            ////創建一個文件流
            //Stream stream=new FileStream(path,FileMode.OpenOrCreate,FileAccess.Write,FileShare.None);

            //formatter.Serialize(stream,student);
            //stream.Close();
              //XML序列化
              this.XmlSerializer();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            //string path = AppDomain.CurrentDomain.BaseDirectory + "/timestamps.txt";
            //Stream stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read);
            //IFormatter formatter = new BinaryFormatter();
            //Student student = (Student)formatter.Deserialize(stream);
            //stream.Close();
            //this.txtResult.Text = "姓名:" + student.Name+"\r\n"
            //                      + "學號:" + student.No + "\r\n"
            //                      + "年齡:" + student.Age + "\r\n"
            //                      + "性別:" + student.Sex;
           //XML反序列化   
            this.XmlDesSerializer();
        }

        private void XmlSerializer()
        {
             //創建一個格式化程序的實例

            XmlSerializer formatter = new XmlSerializer(typeof(Student));
            string path = AppDomain.CurrentDomain.BaseDirectory + "/Student.xml";
            Student me = new Student() 
                         { 
                             No = "200719", 
                             Name = "yuananyun", 
                             Sex="man", 
                             Age=22 
                         }; 
            //創建一個文件流
            Stream stream = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None);
            formatter.Serialize(stream,me);
            stream.Close();
        }

        private void XmlDesSerializer()
        {
            string path = AppDomain.CurrentDomain.BaseDirectory + "/Student.xml";
            Stream stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read);
            XmlSerializer formatter = new XmlSerializer(typeof(Student));
            Student student = (Student)formatter.Deserialize(stream);
            stream.Close();
            this.txtResult.Text = "姓名:" + student.Name + "\r\n"
                                  + "學號:" + student.No + "\r\n"
                                  + "年齡:" + student.Age + "\r\n"
                                  + "性別:" + student.Sex;
        }
    }
}


         

發佈了70 篇原創文章 · 獲贊 4 · 訪問量 10萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章