序列化其實就是將一個對象的所有相關的數據保存為一個二進制文件(注意:是一個對象)
而且與這個對象相關的所有類型都必須是可序列化的所以要在相關類中加上 [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 }
新聞熱點
疑難解答