C#二進制序列化實例分析
更新時間:2015年05月19日 15:22:42 作者:張林春
這篇文章主要介紹了C#二進制序列化,實例分析了C#二進制序列化的方法,代碼中有較為詳盡的注釋說明,便于理解,需要的朋友可以參考下
本文實例講述了C#二進制序列化的方法。分享給大家供大家參考。具體如下:
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization;
namespace WebApplication1.Serialize
{
public partial class Binary1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
//二進制序列化不同于 XMLSerializer 類,后者只序列化公共字段。
protected void Button1_Click(object sender, EventArgs e)
{
MyObject obj = new MyObject();
obj.n1 = 1;
obj.n2 = 24;
obj.str = "Some String";
IFormatter formatter = new BinaryFormatter();
Stream stream = new FileStream("C:/MyFile.bin", FileMode.Create, FileAccess.Write, FileShare.None);
formatter.Serialize(stream, obj);
stream.Close();
}
[Serializable]
public class MyObject
{
public int n1 = 0;
public int n2 = 0;
public String str = null;
}
protected void Button2_Click(object sender, EventArgs e)
{
IFormatter formatter = new BinaryFormatter();
Stream stream = new FileStream("C:/MyFile.bin", FileMode.Open, FileAccess.Read, FileShare.Read);
MyObject obj = (MyObject)formatter.Deserialize(stream);
stream.Close();
// Here's the proof.
Response.Write("n1: {0}"+ obj.n1+"<br/>");
Response.Write("n2: {0}" + obj.n2 + "<br/>");
Response.Write("str: {0}" + obj.str + "<br/>");
}
//上面所用的 BinaryFormatter 非常有效,生成了非常簡潔的字節(jié)流。
//通過該格式化程序序列化的所有對象也可以通過該格式化程序進行反序列化,這使該工具對于序列化將在 .NET Framework 上被反序列化的對象而言十分理想。
//需要特別注意的是,在反序列化一個對象時不調用構造函數。出于性能方面的原因對反序列化施加了該約束。
//但是,這違反了運行庫與對象編寫器之間的一些通常約定,開發(fā)人員應確保他們在將對象標記為可序列化時了解其后果。
//如果可移植性是必需的,則轉為使用 SoapFormatter。
//只需用 SoapFormatter 代替上面代碼中的 BinaryFormatter,
//并且如前面一樣調用 Serialize 和 Deserialize。此格式化程序為上面使用的示例生成以下輸出。
}
}
希望本文所述對大家的C#程序設計有所幫助。
相關文章
Winform動態(tài)加載TabControl用法實例
這篇文章主要介紹了Winform動態(tài)加載TabControl用法,以實例形式詳細講述了Winform動態(tài)加載TabControl的方法,在C#應用程序開發(fā)中具有一定的實用價值,需要的朋友可以參考下2014-11-11
C#難點逐個擊破(6):C#數據類型與.net framework數據類型
最近開始看Illustrator C#2008,這真是一本好書,我讀計算機書籍這么多了,能讓我稱為好書的沒有多少。2010-02-02

