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;
        }
    }
}


         

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值