序列化就是把一個物件轉化成二進位制流儲存起來,當下次使用的使用再反序列化得到資料的原型;
如下例項程式碼:
static void Main(string[] args)
{
//定義一個Book物件
Book book = new Book("Day and Night", 30.0f, "Bruce");
//Book物件序列化
using(FileStream fs = new FileStream(@"C:\book.dat", FileMode.Create))
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(fs, book);
}
book = null;
//反序列化
using(FileStream fs = new FileStream(@"C:\book.dat", FileMode.Open))
book = (Book)formatter.Deserialize(fs);//在這裡大家要注意咯,他的返回值是object
序列化就是把一個物件轉化成二進位制流儲存起來,當下次使用的使用再反序列化得到資料的原型;
如下例項程式碼:
static void Main(string[] args)
{
//定義一個Book物件
Book book = new Book("Day and Night", 30.0f, "Bruce");
//Book物件序列化
using(FileStream fs = new FileStream(@"C:\book.dat", FileMode.Create))
{
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(fs, book);
}
book = null;
//反序列化
using(FileStream fs = new FileStream(@"C:\book.dat", FileMode.Open))
{
BinaryFormatter formatter = new BinaryFormatter();
book = (Book)formatter.Deserialize(fs);//在這裡大家要注意咯,他的返回值是object
}
}