.net完成序列化與反序列化實例解析。本站提示廣大學習愛好者:(.net完成序列化與反序列化實例解析)文章只能為提供參考,不一定能成為您想要的結果。以下是.net完成序列化與反序列化實例解析正文
序列化與反序列化是.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的序列化與反序列化有必定的自創贊助感化。