在C#中實現自定義序列化可以通過實現ISerializable
接口來實現。該接口定義了兩個方法GetObjectData
和ISerializable(SerializationInfo info, StreamingContext context)
。
下面是一個簡單的示例代碼:
using System;
using System.Runtime.Serialization;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
[Serializable]
public class CustomObject : ISerializable
{
public int Id { get; set; }
public string Name { get; set; }
public CustomObject()
{
}
protected CustomObject(SerializationInfo info, StreamingContext context)
{
Id = (int)info.GetValue("Id", typeof(int));
Name = (string)info.GetValue("Name", typeof(string));
}
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("Id", Id);
info.AddValue("Name", Name);
}
}
class Program
{
static void Main()
{
CustomObject obj = new CustomObject
{
Id = 123,
Name = "Custom Object"
};
IFormatter formatter = new BinaryFormatter();
using (Stream stream = new FileStream("data.bin", FileMode.Create, FileAccess.Write, FileShare.None))
{
formatter.Serialize(stream, obj);
}
using (Stream stream = new FileStream("data.bin", FileMode.Open, FileAccess.Read, FileShare.Read))
{
CustomObject deserializedObj = (CustomObject)formatter.Deserialize(stream);
Console.WriteLine($"Id: {deserializedObj.Id}, Name: {deserializedObj.Name}");
}
}
}
在上述示例中,我們定義了一個自定義的CustomObject
類,并實現了ISerializable
接口。在GetObjectData
方法中,我們將需要序列化的數據添加到SerializationInfo
對象中。在構造函數中,我們從SerializationInfo
對象中獲取反序列化的數據。
在Main
方法中,我們創建一個CustomObject
對象并將其序列化保存到文件中。然后再從文件中讀取并反序列化該對象,并輸出結果。