C#自定義序列化反序列化與 ISerializable 接口


ISerializable 接口

MSDN注解:允許對象控制其自己的序列化和反序列化過程。

ISerializable 接口的定義:

public interface ISerializable
{
    void GetObjectData(SerializationInfo info, StreamingContext context);
}

意思就是我們可以通過實現 ISerializable 接口來控制序列化與反序列化后的結果。但是只有使用 BinaryFormatter 時才有用。使用 JavaScriptSerializer 類並沒有效果。下面通過一個示例學習一下。

示例

定義實現 ISerializable 接口的類:

[Serializable]  //記得標記此 Attribute public class Product : ISerializable
{
    private string _name;
    public Product() { }

    public Product(SerializationInfo info, StreamingContext context)
    {
        _name = (String)info.GetValue("Name", typeof(String));
    }

    public String Name
    {
        get { return this._name; }
        set { this._name = value; }
    }

    public void GetObjectData(SerializationInfo info, StreamingContext context)
    {
        info.AddValue("Name", "JRoger.NET",typeof(String));
    }
}

 通過 BinaryFormatter 序列化和反序列化此類:

[Test]
public void SerializableTest()
{
    var product = new Product { Name = "Hello" };
    var formatter = new BinaryFormatter();
    var stream = File.Open(@"E:\Log.bin", FileMode.OpenOrCreate, FileAccess.ReadWrite);

    formatter.Serialize(stream, product);

    stream.Close();
    stream.Dispose();

    var obj = (Product)formatter.Deserialize(File.Open(@"E:\Log.bin", FileMode.OpenOrCreate, FileAccess.ReadWrite));

    Trace.WriteLine(obj.Name);
}

 可以看到,實例化 Product 類時,Name 屬性的值為 "Hello" 而反序列化后輸出結果卻為 "JRoger.NET"。其實控制序列化和反序列化結果的關鍵就是實現 ISerializable 接口。另外實現 ISerializable 接口的類還要有一個帶有兩個參數的構造函數,這兩個參數的類型分別為: SerializationInfoStreamingContext 。

總結

總的來說實現上很簡單,配上示例也很容易。但是使用自定義序列化和反序列化的場景可能並不多。不過作為學習內容還是很有必要的。使用場景少,並不代表沒有。不要放過任何細節。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM