码迷,mamicode.com
首页 > Web开发 > 详细

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

时间:2017-11-13 23:03:28      阅读:261      评论:0      收藏:0      [点我收藏+]

标签:tle   space   序列化   net   ace   alt   point   steam   反序列化   

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

除声明外,跑步客文章均为原创,转载请以链接形式标明本文地址
  .net实现序列化与反序列化实例解析

本文地址:  http://www.paobuke.com/develop/c-develop/pbk23656.html






相关内容

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

标签:tle   space   序列化   net   ace   alt   point   steam   反序列化   

原文地址:http://www.cnblogs.com/paobuke/p/7828160.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!