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]标记,如果该类的成员变量也是一个对象那么该对象也要被标记以此类推都需要做标记。其实序列化与反序列化就是以特定格式的存在本地然后在读出的这么一个过程

 

 

posted @   Smart_Coder  阅读(576)  评论(0编辑  收藏  举报
编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?
点击右上角即可分享
微信分享提示