国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > C# > 正文

.net實現序列化與反序列化實例解析

2020-01-24 02:31:16
字體:
來源:轉載
供稿:網友

序列化與反序列化是.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的序列化與反序列化有一定的借鑒幫助作用。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 甘谷县| 大邑县| 洛阳市| 墨脱县| 庆阳市| 宁陕县| 邵东县| 遂昌县| 青州市| 八宿县| 前郭尔| 喀喇沁旗| 宜兴市| 淮北市| 开封县| 图木舒克市| 蒲城县| 青海省| 无为县| 淳化县| 富裕县| 张北县| 华容县| 威宁| 安远县| 唐海县| 珲春市| 三亚市| 吕梁市| 卢湾区| 汉川市| 定安县| 肥东县| 铜川市| 斗六市| 华蓥市| 台中县| 濮阳县| 泸西县| 城步| 华坪县|