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 上被反序列化的對象而言十分理想。
//需要特別注意的是,在反序列化一個對象時不調(diào)用構(gòu)造函數(shù)。出于性能方面的原因?qū)Ψ葱蛄谢┘恿嗽摷s束。
//但是,這違反了運行庫與對象編寫器之間的一些通常約定,開發(fā)人員應確保他們在將對象標記為可序列化時了解其后果。
//如果可移植性是必需的,則轉(zhuǎn)為使用 SoapFormatter。
//只需用 SoapFormatter 代替上面代碼中的 BinaryFormatter,
//并且如前面一樣調(diào)用 Serialize 和 Deserialize。此格式化程序為上面使用的示例生成以下輸出。
}
}
希望本文所述對大家的C#程序設(shè)計有所幫助。
相關(guān)文章
C#正則表達式分解和轉(zhuǎn)換IP地址實例(C#正則表達式大全 c#正則表達式語法)
這是我發(fā)了不少時間整理的C#的正則表達式,新手朋友注意一定要手冊一下哦,這樣可以節(jié)省很多寫代碼的時間。下面進行了簡單總結(jié)2013-12-12
C#調(diào)用Windows的API實現(xiàn)窗體動畫
在VF、VB、PB的應用中,有些無法通過語言工具本身來完成的或者做得不理想的功能,我們會考慮通過Windows的API來完成。本文就來通過調(diào)用Windows的API實現(xiàn)窗體動畫,感興趣的可以嘗試一下2022-11-11
C#多線程之Thread中Thread.IsAlive屬性用法分析
這篇文章主要介紹了C#多線程之Thread中Thread.IsAlive屬性用法,實例分析了C#判斷線程可用狀態(tài)的技巧,非常具有實用價值,需要的朋友可以參考下2015-04-04

