欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

C#二進(jìn)制序列化實(shí)例分析

 更新時(shí)間:2015年05月19日 15:22:42   作者:張林春  
這篇文章主要介紹了C#二進(jìn)制序列化,實(shí)例分析了C#二進(jìn)制序列化的方法,代碼中有較為詳盡的注釋說明,便于理解,需要的朋友可以參考下

本文實(shí)例講述了C#二進(jìn)制序列化的方法。分享給大家供大家參考。具體如下:

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)
    {
    }
    //二進(jìn)制序列化不同于 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ǎn)潔的字節(jié)流。
    //通過該格式化程序序列化的所有對(duì)象也可以通過該格式化程序進(jìn)行反序列化,這使該工具對(duì)于序列化將在 .NET Framework 上被反序列化的對(duì)象而言十分理想。
    //需要特別注意的是,在反序列化一個(gè)對(duì)象時(shí)不調(diào)用構(gòu)造函數(shù)。出于性能方面的原因?qū)Ψ葱蛄谢┘恿嗽摷s束。
    //但是,這違反了運(yùn)行庫與對(duì)象編寫器之間的一些通常約定,開發(fā)人員應(yīng)確保他們?cè)趯?duì)象標(biāo)記為可序列化時(shí)了解其后果。
    //如果可移植性是必需的,則轉(zhuǎn)為使用 SoapFormatter。
    //只需用 SoapFormatter 代替上面代碼中的 BinaryFormatter,
    //并且如前面一樣調(diào)用 Serialize 和 Deserialize。此格式化程序?yàn)樯厦媸褂玫氖纠梢韵螺敵觥?
  }
}

希望本文所述對(duì)大家的C#程序設(shè)計(jì)有所幫助。

相關(guān)文章

最新評(píng)論