序列化- 使用BinaryFormatter進行序列化

來源:互聯網
上載者:User

可以使用屬性(Attribute)將類的元素標為可序列化的(Serializable)和不可被序列化的(NonSerialized)。.NET中有兩個類實現了IFormatter借口的類中的Serialize和Deserialize方法:BinaryFormatter和SoapFormatter。這兩個類的區別在於資料流的格式不同。

使用BinaryFormatter進行序列化
在下面這個例子中我們建立一個自訂類型(Insect)集合,使用BinaryFormatter將它們寫到二進位檔案,然後再將他們讀回。
註:以下程式需要匯入一些命名空間:
using System;
using System.IO;
using System.Collections;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

[Serializable]
public class Insect
{
    private string name;
    
    [NonSerialized]
    private int id;
    
    public Insect(string name, int id)
    {
        this.name = name;
        this.id= id;
    }
    public override string ToString()
    {
        return String.Format("{0}:{1}", name, id);
    }
}

我們使用一個標準屬性將整個Insect類聲明為可序列化的。但是因為一個欄位被聲明為不可序列化,所以這個欄位不能被持久化。

我們先做一個實驗,我們只執行個體化一個Insect對象,建立一個檔案,然後使用BinaryFormatter對象和Serialize方法寫出這個Insect對象:

class SerializeApp
{
    public static void  Main(string[] args)
    {
        Insect i = new Insect("Meadow Brown", 12);
        Stream sw = File.Create("Insects.bin");
        BinaryFormatter bf = new BinaryFormatter();
        bf.Serialize(sw, i);
        sw.Close();
        }
}

如果在Visual Studio開啟Insect.bin檔案就會看到以下內容:
FBinaryFormatter, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null Insect name Meadow Brown(由於我沒有軟體,所以這隻是部分內容)
我們可以注意到並沒有id欄位,因為它沒有被序列化。

現在,我們增加幾個Insect對象。

        ArrayList box = new ArrayList();
        box.Add(new Insect("Marsh Fritillary", 34));
        box.Add(new Insect("Speckled Wood", 56));
        box.Add(new Insect("Milkweed", 78));
        sw = File.Open("Insects.bin", FileMode.Append);
        bf.Serialize(sw, box);
        sw.Close();
        
        Stream sr = File.OpenRead("Insects.bin");
        Insect j = (Insect)bf.Deserialize(sr);
        Console.WriteLine(j);
        
        ArrayList bag = (ArrayList)bf.Deserialize(sr);
        sr.Close();
        foreach(Insect k in bag)
        {
            Console.WriteLine(k);
        }

下面是這個程式的輸出:
Meadow Brown:0
Marsh Fritillary:0
Speckled Wood:0
Milkweed:0

id值是0,其原因是很明顯的(它在foreach迴圈中構造Insect的期間被初始化為0)。
注意,我們非常小心地先讀回一個Insect對象 - 在讀回集合之前已經被序列化到檔案的對象。
另外,在我們使用Deserialize時,必須對返回的對象進行類型轉換,因為這個方法返回一個一般性的對象。

在後面添加的集合中有三個Insect的資料,這節省了一些開銷,因為只需要為第一列的Insect記錄Insect類的類型資訊。
另外一個有意思的地方是,序列化機制顯然能夠讀寫列中的私人欄位。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.