温馨提示×

如何在C#中实现自定义序列化

c#
小樊
89
2024-08-19 15:02:33
栏目: 编程语言

在C#中实现自定义序列化可以通过实现ISerializable接口来实现。该接口定义了两个方法GetObjectDataISerializable(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对象并将其序列化保存到文件中。然后再从文件中读取并反序列化该对象,并输出结果。

0