栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C# > C#教程

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

C#教程 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

.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的序列化与反序列化有一定的借鉴帮助作用。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/126212.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号