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

首頁 > 編程 > .NET > 正文

.net實(shí)現(xiàn)序列化與反序列化實(shí)例解析

2024-07-10 13:27:58
字體:
供稿:網(wǎng)友
這篇文章主要介紹了.net實(shí)現(xiàn)序列化與反序列化實(shí)例解析,需要的朋友可以參考下
 
 

序列化與反序列化是.net程序設(shè)計(jì)中常見的應(yīng)用,本文即以實(shí)例展示了.net實(shí)現(xiàn)序列化與反序列化的方法。具體如下:

一般來說,.net中的序列化其實(shí)就是將一個(gè)對(duì)象的所有相關(guān)的數(shù)據(jù)保存為一個(gè)二進(jìn)制文件(注意:是一個(gè)對(duì)象)

而且與這個(gè)對(duì)象相關(guān)的所有類型都必須是可序列化的所以要在相關(guān)類中加上 [Serializable]特性

對(duì)象類型包括:對(duì)象本身包含的類型,父類

擁有需要的對(duì)象之后:

1.將對(duì)象轉(zhuǎn)換為二進(jìn)制數(shù)據(jù) 使用專門的對(duì)像進(jìn)行轉(zhuǎn)換 BinaryFormatter

2.將二進(jìn)制數(shù)據(jù)寫入到文件 FileSteam

反序列化則是把二進(jìn)制文件轉(zhuǎn)換為一個(gè)對(duì)象

示例代碼如下所示:

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;//將要被序列化的對(duì)象      Console.WriteLine("------序列化與反序列化------");      Console.WriteLine("是否讀取已經(jīng)序列化的對(duì)象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;//將二進(jìn)制數(shù)據(jù)轉(zhuǎn)換為per對(duì)象          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對(duì)象轉(zhuǎn)換成二進(jìn)制數(shù)據(jù),并保存。          Console.WriteLine("序列化成功");          Console.ReadLine();        }      }            }  }  [Serializable]  class Person  {    public string Name;    public void SayHi()    {      Console.WriteLine("hello {0}",Name);    }  }}

相信本文實(shí)例對(duì)于大家進(jìn)一步理解.net的序列化與反序列化有一定的借鑒幫助作用。


發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 吴川市| 平远县| 九江市| 茂名市| 新安县| 佛山市| 平远县| 玉屏| 黄陵县| 云龙县| 高邑县| 玉山县| 宁强县| 陈巴尔虎旗| 富锦市| 屏东市| 龙游县| 西城区| 龙南县| 泰安市| 丘北县| 孟津县| 石楼县| 德令哈市| 江口县| 嫩江县| 娄底市| 黔东| 稷山县| 龙游县| 张家口市| 逊克县| 神池县| 房产| 水富县| 阳山县| 邵阳县| 论坛| 通城县| 昌都县| 东乌珠穆沁旗|