.net學習筆記--序列化與還原序列化

來源:互聯網
上載者:User

標籤:des   style   blog   color   使用   io   檔案   資料   

序列化其實就是將一個對象的所有相關的資料儲存為一個二進位檔案(注意:是一個對象)

而且與這個對象相關的所有類型都必須是可序列化的所以要在相關類中加上 [Serializable]特性

物件類型包括:對象本神包含的類型,父類

擁有需要的對象之後:1.將對象轉換為位元據 使用專門的對像進行轉換 BinaryFormatter

                                     2.將位元據寫入到檔案 FileSteam

還原序列化則是把二進位檔案轉換為一個對象

例子代碼如下:

 

 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;//將要被序列化的對象15             Console.WriteLine("------序列化與還原序列化------");16             Console.WriteLine("是否讀取已經序列化的對象per");17             string str = Console.ReadLine();18             if (str == "yes")19             {20                 if (!File.Exists("save.bin"))21                 {22                     Console.WriteLine("你還沒有將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;//將位元據轉換為per對象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對象轉換成位元據,並儲存。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 }

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.