序列化 – 實現ISerializable

來源:互聯網
上載者:User
我們可以實現ISerializable介面來自訂序列化行為。這個介面只有一個方法GetObjectData。這個方法用於將對類對象進行序列化所需的資料填進SerializationInfo對象。你使用的格式化器(比如BinaryFormatter)將構造SerializationInfo對象,然後在序列化時調用GetObjectData。因此,你需要實現GetObjectData,讓它添加你從類中選擇的值,並且映射到你選擇的字串名。注意,如果類的父類也實現ISerializable,那麼應該調用GetObjectData的父類實現。
給出例子:using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
[Serializable]
public class Insect : ISerializable
{
    private string name;
    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);
    }
    public Insect(){}
    
    public virtual void GetObjectData(SerializationInfo s, StreamingContext c)
    {
        s.AddValue("CommonName", name);
        s.AddValue("ID#", id);
    }
    private Insect(SerializationInfo s, StreamingContext c)
    {
        name = s.GetString("CommonName");
        id = s.GetInt32("ID#");
    }
}

class ImpISerialApp
{
    static void Main(string[] args)
    {
        Insect i = new Insect("Meadow Brown", 12);
        Stream s = File.Create("Insect.bin");
        BinaryFormatter b = new BinaryFormatter();
        b.Serialize(s, i);
        s.Seek(0, SeekOrigin.Begin);
        Insect j = (Insect)b.Deserialize(s);
        s.Close();
        Console.WriteLine(j);
    }
}

Insect.bin包含以下資訊:
DISerializable, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null Insect
CommonName ID# Meadow Brown

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.