本文實例講述了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 非常有效,生成了非常簡潔的字節流。    //通過該格式化程序序列化的所有對象也可以通過該格式化程序進行反序列化,這使該工具對于序列化將在 .NET Framework 上被反序列化的對象而言十分理想。    //需要特別注意的是,在反序列化一個對象時不調用構造函數。出于性能方面的原因對反序列化施加了該約束。    //但是,這違反了運行庫與對象編寫器之間的一些通常約定,開發人員應確保他們在將對象標記為可序列化時了解其后果。    //如果可移植性是必需的,則轉為使用 SoapFormatter。    //只需用 SoapFormatter 代替上面代碼中的 BinaryFormatter,    //并且如前面一樣調用 Serialize 和 Deserialize。此格式化程序為上面使用的示例生成以下輸出。  }}希望本文所述對大家的C#程序設計有所幫助。
新聞熱點
疑難解答