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

首頁(yè) > 學(xué)院 > 開(kāi)發(fā)設(shè)計(jì) > 正文

.net學(xué)習(xí)筆記--序列化與反序列化

2019-11-14 16:31:00
字體:
來(lái)源:轉(zhuǎn)載
供稿:網(wǎng)友

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

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

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

擁有需要的對(duì)象之后:1.將對(duì)象轉(zhuǎn)換為二進(jìn)制數(shù)據(jù) 使用專(zhuān)門(mén)的對(duì)像進(jìn)行轉(zhuǎn)換 BinaryFormatter

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

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

例子代碼如下:

 

 1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 using System.IO; 7 using System.Runtime.Serialization.Formatters.Binary; 8 namespace Consoleapplication1 9 {10     class PRogram11     {12         static void Main(string[] args)13         {14             Person per;//將要被序列化的對(duì)象15             Console.WriteLine("------序列化與反序列化------");16             Console.WriteLine("是否讀取已經(jīng)序列化的對(duì)象per");17             string str = Console.ReadLine();18             if (str == "yes")19             {20                 if (!File.Exists("save.bin"))21                 {22                     Console.WriteLine("你還沒(méi)有將per序列化");23                     return;24                 }25                 using (FileStream fs = new FileStream("save.bin", FileMode.Open))26                 {27                     BinaryFormatter bf = new BinaryFormatter();28                     per = bf.Deserialize(fs) as Person;//將二進(jìn)制數(shù)據(jù)轉(zhuǎn)換為per對(duì)象29                     per.SayHi();30                     Console.ReadLine();31                 }32             }33             else34             {35                 per = new Person();36                 per.Name = "小李";37                 using(FileStream fs=new FileStream("save.bin",FileMode.Create))38                 {39                     BinaryFormatter bf = new BinaryFormatter();40                     bf.Serialize(fs,per);//將per對(duì)象轉(zhuǎn)換成二進(jìn)制數(shù)據(jù),并保存。41                     Console.WriteLine("序列化成功");42                     Console.ReadLine();43                 }44             }45                 49         }50     }51     [Serializable]52     class Person53     {54         public string Name;55         public void SayHi()56         {57             Console.WriteLine("hello {0}",Name);58         }59     }60 }

 


發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 芜湖县| 桐庐县| 犍为县| 马公市| 永登县| 库车县| 峡江县| 馆陶县| 鹿邑县| 云龙县| 九龙县| 承德市| 若尔盖县| 永登县| 昭平县| 平乐县| 福安市| 临猗县| 伊通| 林周县| 邵阳县| 二连浩特市| 元谋县| 皮山县| 建宁县| 项城市| 汝城县| 孝昌县| 广平县| 六枝特区| 化隆| 行唐县| 高唐县| 灵武市| 九寨沟县| 鄢陵县| 大足县| 临安市| 桦川县| 宜宾市| 革吉县|