百度首页 | 百度空间
 
查看文章
 
序列化和反序列化
2008年06月22日 星期日 21:51

序列化是将对象状态转换为可保持或传输的格式的过程。与序列化相对的是反序列化,它将流转换为对象。这两个过程结合起来,就使得数据能够被轻松地存储和传输。简单点来理解就是把内存的东西写到硬盘中,当然也可以写到内存中.反序列化就是从硬盘中把信息读到内存中.

[例1:CSDN blucexi专栏]

定义类Book:

[Serializable]
public class Book
{
            string name;
            float     price;
            string author;

           public Book(string bookname, float bookprice, string bookauthor)
           {
                   name = bookname;
                   price = bookprice;
                   author = bookauthor;
            }
}

在类的上面增加了属性:Serializable.(如果不加这个属性,将抛出SerializationException异常).

通过这个属性将Book标志为可以序列化的.当然也有另一种方式使类Book可以序列化,那就是实行ISerializable接口了.

如果你不想序列化某个变量,该怎么处理呢?很简单,在其前面加上属性[NonSerialized] .比如我不想序列化 string author,那我只需要:

[NonSerialized]
string author;

using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

//实例化一个Book
Book book = new Book("Day and Night", 30.0f, "Bruce");

//创建一个文件了,用来存放要序列化的信息了.
FileStream fs = new FileStream(@"C:\book.dat", FileMode.Create);

//序列化的实现
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(fs, book);


//列出整个原代码,包括反序列化.
static void Main(string[] args)
{
Book book = new Book("Day and Night", 30.0f, "Bruce");

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
}
}

[例2:CSDN]

using System.IO;   
using System.Runtime.Serialization.Formatters.Binary;   

[Serializable()] //可以序列化的类需要用这个属性标记   
public class ToBeSerialized   
{   
           public int a;   
           public string b;   
           public ToBeSerialized(int a,string b)   
           {   
                   this.a=a;   
                   this.b=b;   
           }   
}   

public class Test   
{   
           public void Serialize() //序列化   
           {   
                   ToBeSerialized tbs = new ToBeSerialized(22,"SOM");   
                   Stream fs = File.Create("Serialized.txt");   
                   BinaryFormatter serializer = new BinaryFormatter();   
                   serializer.Serialize(fs, tbs);   
                   fs.Close();   
           }   
           public void DeSerialize() //反序列化   
           {   
                   ToBeSerialized restore;   
                   Stream fs = File.OpenRead("Serialized.txt");   
                   BinaryFormatter deserializer = new BinaryFormatter();   
                   restore = (ToBeSerialized)(deserializer.Deserialize(fs)); //反序列化得到的对象   
                   fs.Close();   
           }   
}


类别:.net | 添加到搜藏 | 浏览() | 评论 (0)
 
最近读者:
 
网友评论:
发表评论:
姓 名:
网址或邮箱: (选填)
内 容:
验证码:
 

     

©2008 Baidu