序列化(serialization)描述了持久化(可能还包括传输)一个对象的状态到流的过程。被持久化的数据次序包括所有以后需要用来重建(即反序列化)对象状态所必需的信息。
? 序列化简单点来理解就是把内存的东西写到硬盘中。
? 实现方法:IFormatter接口中的Serialize和Deserialize方法。
? 命名空间:
? using System.Runtime.Serialization;
? 一般说来,在两种情况下非常需要Serialization:
? 1)当我们希望能够将对象当前的状态完整地保存到存储介质中,以便我们以后能够精确地还原对象时;
? 2)当我们希望将对象从一个应用程序空间(Application domain)传递到另一个应用程序空间时
Serializable属性是不能被继承的,因此,如果从被标记为[Serializable]的类派生一个类,子类也必须被标记为[Serializable],否则它不能被持久化;
? 如果你不想序列化某个成员,在其前面加上属性[NonSerialized];
? 如果试图序列化一个非序列化的对象,在运行时将会收到一个SerializationException(序列化异常)的提示。
三种对象序列化程序
为了让一个对象支持.NET序列化服务,用户需要做的只是为每一个关联的类加上[Serializable]特性;
?一旦将类型配置为参与.NET序列化,接下来就是选择当持久化对象图时使用哪种格式。在.NET 2.0中,有以下三种选择:
?BinaryFormatter
?SoapFormatter
?XmlSerializer
BinaryFormatter
BinaryFormatter类型使用紧凑的二进制格式将对象图序列化为一个流,这个类型在System. Runtime.Serialization.Formatters.Binary命名空间中定义,后者是mscorlib.dll的一部分。因此,为了使用二进制序列化对象,需要指定下面的C# using指令:
?// 获取对mscorlib.dll中的BinaryFormatter的访问
?Using System.Runtime.Serialization.Formatters.Binary;
Book.cs位于App_Code中
using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
/// <summary>
///Book 的摘要说明
/// </summary>
[Serializable]
public class Book
{
public Book()
{
//
//TODO: 在此处添加构造函数逻辑
//
}
[NonSerialized]
private string name;
private float price;
private string author;
public Book(string bookname, float bookprice, string bookauthor)
{
name = bookname;
price = bookprice;
author = bookauthor;
}
public override string ToString()
{
return "书名:"+name+"价格:"+price+"作者:"+author;
}
}
Demo:BinaryFormatter.aspx
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
序列化
//Book book = new Book("C#编程基础", 90, "Tom");
//IFormatter formatter = new BinaryFormatter();
//Stream stream = new FileStream(@"D://myfile.txt",FileMode.Create,FileAccess.Write,FileShare.None);