在C#中,可以通過(guò)實(shí)現(xiàn)ISerializable
接口來(lái)自定義序列化過(guò)程。以下是一個(gè)簡(jiǎn)單的示例代碼:
using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
[Serializable]
public class CustomObject : ISerializable
{
public int Id { get; set; }
public string Name { get; set; }
public CustomObject() { }
public CustomObject(int id, string name)
{
Id = id;
Name = name;
}
// 實(shí)現(xiàn)ISerializable接口的GetObjectData方法
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("Id", Id);
info.AddValue("Name", Name);
}
// 自定義的反序列化方法
public CustomObject(SerializationInfo info, StreamingContext context)
{
Id = (int)info.GetValue("Id", typeof(int));
Name = (string)info.GetValue("Name", typeof(string));
}
}
public class Program
{
public static void Main()
{
CustomObject obj = new CustomObject(1, "Object1");
// 序列化對(duì)象
IFormatter formatter = new BinaryFormatter();
using (Stream stream = new FileStream("data.bin", FileMode.Create, FileAccess.Write, FileShare.None))
{
formatter.Serialize(stream, obj);
}
// 反序列化對(duì)象
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}");
}
}
}
在上面的示例中,我們創(chuàng)建了一個(gè)自定義的CustomObject
類,并實(shí)現(xiàn)了ISerializable
接口。在GetObjectData
方法中,我們將需要序列化的數(shù)據(jù)添加到SerializationInfo
對(duì)象中。在自定義的反序列化構(gòu)造函數(shù)中,我們獲取SerializationInfo
對(duì)象中的數(shù)據(jù)來(lái)重新構(gòu)造對(duì)象。
通過(guò)這種方式,我們可以完全控制對(duì)象的序列化和反序列化過(guò)程,實(shí)現(xiàn)自定義的序列化邏輯。