C# 序列化与反序列化

我们先说说什么是序列化。所谓的序列化就是把要保存的内容以特定的格式存入某种介质中。比如我们要保存一些数据在下次程序启动的时候再读入。我们一般就是把这个数据写在一个本地的文本中。然后程序启动的时候去读入这个文本。这是我们自己写的。微软为我们想的很好它给我们写了一个这样一个类,不用我们自己去写。反序列化就是把序列化的字符给读出加载;话不多说先上列子:

 ///////////////////////////////////////MyPerson这个类////////////////////////////////////////

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

namespace 序列化和反序列化

{    

  [Serializable]     //要被序列化的类必须被标记

  public class MyPerson    

  {        

    public string Name { get; set; }        

    public int Age { get; set; }

         public MyPerson()        

    {                    

    }    

  }

}

///////////////////////////////////////////////主体/////////////////////////////////////////////////////

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using System.IO;

namespace 序列化和反序列化

{    

   class Program    

  {        

    static void Main(string[] args)        

     {            

      #region 把对象序列化            

      using (FileStream fs = new FileStream("1.txt", FileMode.Create))            

       {

                  MyPerson myp = new MyPerson();                

         myp.Name = "媳妇";                

        myp.Age = 22;                

        System.Runtime.Serialization.Formatters.Binary.BinaryFormatter b = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();                 

        b.Serialize(fs, myp);            

      }            

       #endregion

              #region 反序列化出对象            

      using(FileStream fs = new FileStream("1.txt",FileMode.Open))            

      {                

        System.Runtime.Serialization.Formatters.Binary.BinaryFormatter b = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();

                  object o = b.Deserialize(fs);                

        MyPerson m = o as MyPerson;            

       }            

       #endregion        

    }    

  }

}

注*要被序列化的对象必须进行[Serializable]标记,如果该类的成员变量也是一个对象那么该对象也要被标记以此类推都需要做标记。其实序列化与反序列化就是以特定格式的存在本地然后在读出的这么一个过程

原文地址:https://www.cnblogs.com/gaojiangshan/p/3286774.html