.net实现序列化与反序列化实例解析

序列化与反序列化是.net程序设计中常见的应用,本文即以实例展示了.net实现序列化与反序列化的方法。具体如下:

一般来说,.net中的序列化其实就是将一个对象的所有相关的数据保存为一个二进制文件(注意:是一个对象)

而且与这个对象相关的所有类型都必须是可序列化的所以要在相关类中加上 [Serializable]特性

对象类型包括:对象本身包含的类型,父类

拥有需要的对象之后:

1.将对象转换为二进制数据 使用专门的对像进行转换 BinaryFormatter

2.将二进制数据写入到文件 FileSteam

反序列化则是把二进制文件转换为一个对象

示例代码如下所示:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
namespace ConsoleApplication1
{
  class Program
  {
    static void Main(string[] args)
    {
      Person per;//将要被序列化的对象
      Console.WriteLine("------序列化与反序列化------");
      Console.WriteLine("是否读取已经序列化的对象per");
      string str = Console.ReadLine();
      if (str == "yes")
      {
        if (!File.Exists("save.bin"))
        {
          Console.WriteLine("你还没有将per序列化");
          return;
        }
        using (FileStream fs = new FileStream("save.bin", FileMode.Open))
        {
          BinaryFormatter bf = new BinaryFormatter();
          per = bf.Deserialize(fs) as Person;//将二进制数据转换为per对象
          per.SayHi();
          Console.ReadLine();
        }
      }
      else
      {
        per = new Person();
        per.Name = "小李";
        using(FileStream fs=new FileStream("save.bin",FileMode.Create))
        {
          BinaryFormatter bf = new BinaryFormatter();
          bf.Serialize(fs,per);//将per对象转换成二进制数据,并保存。
          Console.WriteLine("序列化成功");
          Console.ReadLine();
        }
      }
        
    }
  }
  [Serializable]
  class Person
  {
    public string Name;
    public void SayHi()
    {
      Console.WriteLine("hello {0}",Name);
    }
  }
}

相信本文实例对于大家进一步理解.net的序列化与反序列化有一定的借鉴帮助作用。